【问题标题】:Linq to Object combine 2 arrays in one as one to manyLinq to Object 将 2 个数组合二为一,一对多
【发布时间】:2014-12-17 10:54:33
【问题描述】:

我有 2 个列表,下一个类型为 IList<string>IList<int> 例如,我在第一个列表中有下一个值

AA
BB
CC

在其他数组中

1
2

我想获得包含下一个结果的组合列表

AA 1
BB 1
CC 1
AA 2
BB 2
CC 2

是否可以仅使用 LINQ to Object ?

【问题讨论】:

  • 你想要什么结果?字符串列表?

标签: c# linq linq-to-objects


【解决方案1】:

如果顺序无关紧要,那么:

from left in new List<string>{"AA", "BB", "CC"}
from right in new List<string>{"1", "2"}
   select string.Format("{0} {1}", left, right)

哪个输出:

AA 1 
AA 2 
BB 1 
BB 2 
CC 1 
CC 2 

称为笛卡尔积:Is there a good LINQ way to do a cartesian product?

【讨论】:

【解决方案2】:

如果你想要一个字符串列表作为结果,这应该可以解决问题:

var result = numbers
    .SelectMany(x => letters.Select(l => string.Join(" ", l, x)).ToList();

【讨论】:

    【解决方案3】:

    试试这个:

    static void Main(string[] args)
    {
       List<string> firstList = new List<string>();
       firstList.Add("AA");
       firstList.Add("BB");
       firstList.Add("CC");
    
       List<int> secondList = new List<int>();
       secondList.Add(1);
       secondList.Add(2);
    
       var lstFinal = (from f1 in firstList
                       from f2 in secondList
                       select new { f1, f2 }).ToList();
       foreach (var s in lstFinal)
       {
           Console.WriteLine(s.f1 + " " +s.f2);
       }
       Console.Read();
    }
    

    输出:

    AA 1 
    AA 2 
    BB 1 
    BB 2 
    CC 1 
    CC 2 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多