生成n元笛卡尔乘积例子 [英] Generating a n-ary Cartesian product example

查看:136
本文介绍了生成n元笛卡尔乘积例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

现在的问题是,我不能环绕我应该如何使用它与一个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次);
 

解决方案

样品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();

这篇关于生成n元笛卡尔乘积例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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