简体   繁体   中英

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

I have three 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" };

And i want multiple combination among all of above three list like

ACF
ACG
ADF
ADG
...

I tried SelectMany and Zip but did't work.

Note: An help would be appreciate if I get my desired output by using lambda expression.

You can do this by using Join like

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

Output:

在此处输入图片说明

you need 3 loops:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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