Ali Ghanaatpisheh
Ali Ghanaatpisheh

Reputation: 311

Zipping two lists in C#

I have two lists of Integer values:

List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> list2 = new List<int>() { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };

I want to zip the above two lists so that the elements in even index are obtained from the sum of corresponding elements in List 1 and List 2 and the odd elements are obtained by multiplying them, I tried to do something like this but it did't work:

list1.Zip(list2, index => index % 2 == 0 ? (a, b) => a + b : (a, b) => a * b );

desired output

{ 12,24,16,56,20,96,24,144,28,200 }

Upvotes: 1

Views: 2566

Answers (4)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23228

Zip method doesn't have overload which supports index, you can use MoreLinq library or Select method instead (with element selector, which supports index)

var result = list1.Select(
        (value, index) =>
            index % 2 == 0 ? value + list2[index] : value * list2[index])
    .ToList();
result.ForEach(Console.WriteLine);

It'll work if both lists have the same length and give you an expected output 12, 24, 16, 56, 20, 96, 24, 144, 28, 200

Another option is to Zip both lists into list of anonymous objects, then calculate the sum against them

var result = list1
    .Zip(list2, (a, b) => new { a, b })
    .Select((value, index) => index % 2 == 0 ? value.a + value.b : value.a * value.b)
    .ToList();

Upvotes: 3

Alexander Petrov
Alexander Petrov

Reputation: 14231

Another option:

int index = 0;
var zipped = list1.Zip(list2, (a, b) => index++ % 2 == 0 ? a + b : a * b);

Succinctly, but it uses a side effect, which is of course bad.

Upvotes: 1

juharr
juharr

Reputation: 32266

You can Zip first then use the overload of Select that includes the index.

var result = list1.Zip(list2, (a,b) => (A:a, B:b))
    .Select((x, i) => i % 2 == 0 ? x.A + x.B : x.A * x.B);

Note I'm using value tuples here, so depending on your version of C# you might need to use anonymous classes instead (a,b) => new { A=a, B=b }

Upvotes: 7

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

Use .Select() instead of Zip

var result = list1.Select((e, i) =>
                 i % 2 == 0 ?  e + list2[i] : e * list2[i])
                 .ToList()

Upvotes: 1

Related Questions