Search code examples
c#listmergeconvertall

C# merge two lists into one list like Enumerable.ConvertAll


I want to convert two lists with the same index into a single list. Given this:

List<double> ListA = new List<double> {  1,  2,  3,  4,  5  };
List<string> ListB = new List<string> { "A","B","C","D","E" };

until now, I used this:

List<string> UNHAPPY = new List<string>();
for (int ListIndex = 0; ListIndex < ListA.Count; ListIndex++)
{
    UNHAPPY.Add(ListB[ListIndex]+ListA[ListIndex].ToString());
}
// such that UNHAPPY == new List<string> {"A1", "B2", "C3", "D4", "E5"}

But I really want to use short code as possible, like this (Similar to Enumerable.ConvertAll):

List<string> HAPPY = SOME_CONTAINER(ListA, ListB).SOME_SELECTOR((a,b) => b + a.ToString());

// such that HAPPY == new List<string> {"A1", "B2", "C3", "D4", "E5"}

Is there any quick method for this? Thank you so mush in advance!


Solution

  • LINQ has a method for this, it's called Zip:

    var res = ListA.Zip(ListB, (a,b) => $"{b}{a}");
    

    It takes two sequences and a Func delegate, and applies the delegate to pairs of items coming from the two sequences.

    Note: call of ToString on a is redundant, C# will concatenate a string to anything, including an int, by calling ToString on the corresponding object. I prefer string interpolation, especially when you need to concatenate more than two items.