【问题标题】:How to get multiple combination of items from multiple list in c#如何从C#中的多个列表中获取多个项目组合
【发布时间】:2018-09-22 20:30:19
【问题描述】:

我有三个列表

 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
...

我尝试了SelectMany 和Zip,但没有成功。

注意:如果我使用 lambda 表达式获得所需的输出,我们将不胜感激。

【问题讨论】:

标签: c# list


【解决方案1】:

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

输出:

【讨论】:

    【解决方案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]);
    

    【讨论】:

    • 我想用最少的代码行得到结果。谢谢你的回复:)
    • 最少的代码行数并不总是最好的。觉得它可能看起来更整洁。
    猜你喜欢
    • 1970-01-01
    • 2011-01-19
    • 2019-03-20
    • 2020-11-27
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多