使用Linq和C#创建列表中项目的所有可能组合

前端之家收集整理的这篇文章主要介绍了使用Linq和C#创建列表中项目的所有可能组合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个类别表:
Catid | Desciption
 1 | Color
 2 | Size
 3 | Material

和一个类别项目表

Catid | Name
 1 | Red
 1 | Blue
 1 | Green
 2 | Small
 2 | Med
 2 l Large
 3 | Cotton
 3 | Silk

我需要遍历所有项目并将其显示在这样的标签中:

Red Small Cotton
 Red Small Silk
 Red Med Cotton
 Red Med Silk
 Red Large Cotton
 Red Large Silk
 Blue Small Cotton
 Blue Small Silk
 Blue Med Cotton
 Blue Med Silk
 Blue Large Cotton
 Blue Large Silk
 Green Small Cotton
 Green Small Silk
 Green Med Cotton
 Green Med Silk
 Green Large Cotton
 Green Large Silk

请注意:可能有更多或更少的类别.这不是预先确定的.

有什么建议?
谢谢

解决方法

var result = list.GroupBy(t => t.Id).CartesianProduct();

使用Eric Lippert’s Blog CartesianProduct Extension Method

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})); 
}

例:

var list = new[]
{
    new { Id = 1,Description = "Red"    },new { Id = 1,Description = "Blue"   },Description = "Green"  },new { Id = 2,Description = "Small"  },Description = "Med"    },Description = "Large"  },new { Id = 3,Description = "Cotton" },Description = "Silk"   },};

var result = list.GroupBy(t => t.Id).CartesianProduct();

foreach (var item in result)
{
    Console.WriteLine(string.Join(" ",item.Select(x => x.Description)));
}

输出

Red Small Cotton
Red Small Silk
Red Med Cotton
Red Med Silk
Red Large Cotton
Red Large Silk
Blue Small Cotton
Blue Small Silk
Blue Med Cotton
Blue Med Silk
Blue Large Cotton
Blue Large Silk
Green Small Cotton
Green Small Silk
Green Med Cotton
Green Med Silk
Green Large Cotton
Green Large Silk
原文链接:https://www.f2er.com/csharp/98858.html

猜你在找的C#相关文章