简体   繁体   English

合并2个列表的最佳方法

[英]Best way to combine 2 lists

I have the below 2 list: 我有以下2个清单:

List<string> a = new List<string>()
{
    "a",
    "b"
};

List<string> b = new List<string>()
{
    "c",
    "d"
};

What is the best way to combine a and b to get the following: 结合ab获得以下内容的最佳方法是什么:

{
    "ac",
    "ad",
    "bc",
    "bd"
};

Is there a LINQ function that enables us to do the above? 是否有使我们能够执行上述操作的LINQ函数?

I don't know that asking for the "best way" is the best way to ask a question (bad pun intended), since there will usually be multiple ways. 我不知道问“最好的方式”是提出问题的最佳方式(因为故意说双关语),因为通常会有多种方式。

What you need is to loop through the first list and then, for each element, loop through the second list, so you can find every combination of the two. 您需要的是遍历第一个列表,然后对于每个元素,遍历第二个列表,这样您就可以找到两者的每种组合。

One possible way is to use LINQ's SELECT statement: 一种可能的方法是使用LINQ的SELECT语句:

var combination = a.Select(first => b.Select(second => first + second))
                   .SelectMany(x => x)
                   .ToList();

You could also just use a couple nested foreach loops, which may not be as elegant looking as some LINQ implementations but is most likely just as efficient. 您也可以只使用几个嵌套的foreach循环,它们看起来可能不像某些LINQ实现那样优雅,但很有可能效率很高。

var combination = new List<string>();

foreach(var first in a)
    foreach (var second in b)
        combination.Add(first+second);

Can try: 可以尝试:

    List<string> c = new List<string>();

    for(int i=0; i<a.Count; i++){
        for(int j=0; j< b.Count; j++){
            c.Add(a[i]+b[j]);
        }
    }

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

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