Hisham Maudarbocus
Hisham Maudarbocus

Reputation: 620

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?

Upvotes: 0

Views: 111

Answers (2)

Noor A Shuvo
Noor A Shuvo

Reputation: 2817

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

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66501

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

Upvotes: 3

Related Questions