简体   繁体   中英

Best way to combine 2 lists

I have the below 2 list:

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:

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

Is there a LINQ function that enables us to do the above?

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:

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.

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

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