是否有一个良好的LINQ的方式做一个笛卡尔积? [英] Is there a good LINQ way to do a cartesian product?

查看:312
本文介绍了是否有一个良好的LINQ的方式做一个笛卡尔积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类结构如下所示:

I have a class structure like so:

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

有一人。他有1..N犬。每个狗1..1小狗。

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小狗,狗2小狗
狗小狗1 A,狗2小狗乙
狗小狗1 B,狗2小狗
狗小狗1 B,狗小狗2乙

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十岁上下的方式做到这一点有点儿事???

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:

<一个href=\"http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/\">http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/

和这个计算器的问题:

生成所有可能的组合

一旦你的方法笛卡儿积&LT; T&GT; 那么你可以说

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天全站免登陆