生成n元笛卡尔乘积例子笛卡尔、乘积、例子

由网友(此生、詠别)分享简介:我发现,这里埃里克利珀的帖子 适合特定的问题,我有。现在的问题是,我不能环绕我应该如何使用它与一个2 +量藏品我的头。有VAR集合=新的名单,其中,名单,其中,MyType的>>();的foreach(在somequery VAR项){collections.Add(新名单,其中,MyType的>...

我发现,这里埃里克利珀的帖子 适合特定的问题,我有。

现在的问题是,我不能环绕我应该如何使用它与一个2 +量藏品我的头。

  VAR集合=新的名单,其中,名单,其中,MyType的>>();
的foreach(在somequery VAR项)
{
    collections.Add(
            新名单,其中,MyType的> {新的MyType {n = 1} ... N}
        );
}
 

如何申请笛卡尔乘积LINQ查询上的集合的variabile的?

的扩展方法是这样:

 静态的IEnumerable< IEnumerable的< T>> CartesianProduct< T>(这IEnumerable的< IEnumerable的< T>>序列)
{
    IEnumerable的< IEnumerable的< T>> emptyProduct =新的[] {Enumerable.Empty< T>()};
    返回sequences.Aggregate(
        emptyProduct,
        (累加器,序列)=>
            从accseq累加器
            从顺序题目
            选择accseq.Co​​ncat(新[] {}项)
        );
 }
 

下面是Eric的例子2集:

  VAR ARR1 =新的[] {A,B,C};
变种ARR2 =新[] {3,2,4};
VAR的结果=从cpLine在CartesianProduct(
                     从ARR2选择Enumerable.Range计数(1计数))
             选择cpLine.Zip(ARR1,(X1,X2)=> 2 + 1次);
 
mysql oracle中的各种join连接用法 整理

解决方案

样品code已经能够做到N笛卡尔乘积(它3中的例子)。你的问题是,你有一个名单,其中,名单,其中,MyType的>> 当你需要一个的IEnumerable< IEnumerable的< MyType的>>

 的IEnumerable< IEnumerable的< MyType的>>结果=集合
  。选择(名单=> list.AsEnumerable())
  .CartesianProduct();
 

I found that Eric Lippert's post here suits a particular problem I have.

The problem is I can't wrap my head around how I should be using it with a 2+ amount of collections.

Having

var collections = new List<List<MyType>>();
foreach(var item in somequery)
{
    collections.Add(
            new List<MyType> { new MyType { Id = 1} .. n }
        );
}

How do I apply the cartesian product linq query on the collections variabile ?

The extension method is this one:

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
    IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>()};
    return sequences.Aggregate(
        emptyProduct,
        (accumulator, sequence) => 
            from accseq in accumulator 
            from item in sequence 
            select accseq.Concat(new[] {item})                       
        );
 }

Here is Eric's example for 2 collections:

var arr1 = new[] {"a", "b", "c"};
var arr2 = new[] { 3, 2, 4 };
var result = from cpLine in CartesianProduct(
                     from count in arr2 select Enumerable.Range(1, count)) 
             select cpLine.Zip(arr1, (x1, x2) => x2 + x1);

解决方案

The sample code is already able to do "n" cartesian products (it does 3 in the example). Your problem is that you have a List<List<MyType>> when you need an IEnumerable<IEnumerable<MyType>>

IEnumerable<IEnumerable<MyType>> result = collections
  .Select(list => list.AsEnumerable())
  .CartesianProduct();

阅读全文

相关推荐

最新文章