如何从C#中的多个列表中获取项目的多个组合

时间:2018-09-21 12:05:52

标签: c# list

我有三个列表

 List<string> firstList = new List<string> { "A", "B" };
 List<string> secondList = new List<string> { "C", "D", "E" };
 List<string> thirdList = new List<string> { "F", "G" };

我想在上述三个列表中的所有组合

ACF
ACG
ADF
ADG
...

我尝试了SelectManyZip,但是没有用。

注意:如果我使用lambda表达式获得所需的输出,将对您有所帮助。

2 个答案:

答案 0 :(得分:5)

您可以使用Join之类的方法来

public class Program
{
    static void Main(string[] args)
    {
        List<string> firstList = new List<string> { "A", "B" };
        List<string> secondList = new List<string> { "C", "D", "E" };
        List<string> thirdList = new List<string> { "F", "G" };

        List<string> result = firstList
                              .Join(secondList, x => true, y => true, (m, n) => m + n)
                              .Join(thirdList, a => true, b => true, (a, b) => a + b)
                              .ToList();

        result.ForEach(x => Console.WriteLine(x));
        Console.ReadLine();
    }
}

输出:

enter image description here

答案 1 :(得分:2)

您需要3个循环:

List<string> combinations = new List<string>();
for(int i=0; i < firstList.Length; i++)
   for(int j=0;j < secondList.Length; j++)
      for(int k=0;k < thirdList.Length; k++)
            combinations.Add(firstList[i]+secondList[j]+thirdList[k]);