有没有一种很好的 LINQ 方法来做笛卡尔积? [英] Is there a good LINQ way to do a cartesian product?

查看:26
本文介绍了有没有一种很好的 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:

http://ericlippert.com/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 方法来做笛卡尔积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆