繁体   English   中英

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

[英]How to get multiple combination of items from multiple list in c#

我有三个清单

 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表达式获得所需的输出,将对您有所帮助。

您可以通过像这样使用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();
    }
}

输出:

在此处输入图片说明

您需要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]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM