有没有一种很好的 LINQ 方法来做笛卡尔积?

编程入门 行业动态 更新时间:2024-10-15 12:29:00
本文介绍了有没有一种很好的 LINQ 方法来做笛卡尔积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个这样的类结构:

I have a class structure like so:

Person Dogs (dog 1, dog 2, etc) Puppies (puppy A, puppy B, etc)

只有一个人.他有 1..n 条狗.每只狗有 1..n 只小狗.

There is one person. He has 1..n dogs. Each dog has 1..n puppies.

我想要一份所有可能的小狗组合的列表,从每只狗身上取 1 只小狗.例如:

I want a list of all the possible combination of puppies, taking 1 puppy from each dog. Eg:

狗1小狗A,狗2小狗A狗 1 小狗 A,狗 2 小狗 B狗 1 小狗 B,狗 2 小狗 A狗1小狗B,狗2小狗B

dog 1 puppy A, dog 2 puppy A dog 1 puppy A, dog 2 puppy B dog 1 puppy B, dog 2 puppy A dog 1 puppy B, dog 2 puppy B

如果它在 sql 表中,我会执行以下操作来乘以"表:

If it was in sql tables, i'd do something like the following to 'multiply' the tables:

select * from puppies a, puppies b where a.parent='dog1' and b.parent='dog2'

有没有什么 linq-ish 的方式来做这种事情???

Is there some linq-ish way to do this kinda thing???

非常感谢

推荐答案

如果我理解这个问题,你想要 n 组小狗的笛卡尔积.

If I understand the question, you want the Cartesian Product of n sets of puppies.

如果您在编译时知道有多少个集合,就很容易得到笛卡尔积:

It is easy to get the Cartesian Product if you know at compile time how many sets there are:

from p1 in dog1.Puppies from p2 in dog2.Puppies from p3 in dog3.Puppies select new {p1, p2, p3};

假设dog1有小狗p11、p12,dog2有小狗p21,dog3有小狗p31、p32.这给你

Suppose dog1 has puppies p11, p12, dog2 has puppy p21, and dog3 has puppies p31, p32. This gives you

{p11, p21, p31}, {p11, p21, p32}, {p12, p21, p31}, {p12, p21, p32}

其中每一行都是匿名类型.如果您在编译时不知道有多少组,您可以多做一点工作.请参阅我关于该主题的文章:

Where each row is an anonymous type. If you do not know at compile time how many sets there are, you can do that with slightly more work. See my article on the subject:

ericlippert/2010/06/28/computing-a-cartesian-product-with-linq/

还有这个 StackOverflow 问题:

and this StackOverflow question:

生成所有可能的组合

一旦你有了方法 CartesianProduct 然后你就可以说

Once you have the method CartesianProduct<T> then you can say

CartesianProduct(from dog in person.Dogs select dog.Puppies)

得到

{p11, p21, p31}, {p11, p21, p32}, {p12, p21, p31}, {p12, p21, p32}

其中每一行是一系列小狗.

Where each row is a sequence of puppies.

有意义吗?

更多推荐

有没有一种很好的 LINQ 方法来做笛卡尔积?

本文发布于:2023-11-23 18:53:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622517.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:笛卡尔   很好   来做   方法   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!