如何打印或显示两个字符串列表的所有组合[重复]

问题描述 投票:-2回答:3

目前我有2个清单。例如:

List1
A
B
C

List2
a
b
c
d

期望输出为

Col1  Col2
A      a
A      b
A      c
A      d
B      a
B      b
B      c
B      d
C      a
C      b
C      c
C      d

如何生成这样的?

目前我有2个清单。例如:

List
A
B
C

List
a
b
c
d

我需要输出为

Col1  Col2
A      a
A      b
A      c
A      d
B      a
B      b
B      c
B      d
C      a
C      b
C      c
C      d
c# html
3个回答
0
投票

使用简单的LINQ来迭代这两个列表

List<string> list1 = new List<string> { "A", "B", "C" };
List<string> list2 = new List<string> { "a", "b", "c", "d" };


var result = (from x in list1
              from y in list2
              select new
              {
                  Col1 = x,
                  Col2 = y
              }).ToList();


Console.WriteLine("Col1 \t Col2");

result.ForEach(x => Console.WriteLine(x.Col1 + "\t" + x.Col2));

Console.ReadLine();

输出:

enter image description here


0
投票
List<string> list1 = new List<string>() { "A", "B", "C" };
            List<string> list2 = new List<string>() { "a", "b", "c", "d"};

            list1.ForEach(res =>
            {
                list2.ForEach(res1 =>
                {
                    Console.WriteLine(res + "  " + res1);
                });
            });

输出是:

Output


0
投票

正如我可以从您的问题中找到的那样,您可以使用两个嵌套循环来完成它。但是如果要创建组合列表,可以使用以下代码:

IList<string> List1 = new List<string>() { "A", "B", "C"};
IList<string> List2 = new List<string>() { "a", "b", "c", "d"};
IList<string> combination = List1.SelectMany(g => List2.Select(c => new { Value = g.ToString() + c.ToString() })).Select(a => a.Value).ToList(); 
foreach (var c in combination)
{
     Console.WriteLine(c); 
}
© www.soinside.com 2019 - 2024. All rights reserved.