Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to most elegantly iterate through parallel collections in C#?

        var a = new Collection<string> {"a", "b", "c"};
        var b = new Collection<int> { 1, 2, 3 };

What is the most elegant way to iterate through both yielding a set of results "a1", "b2", "c3"?

like image 278
Sergey Aldoukhov Avatar asked Nov 30 '22 19:11

Sergey Aldoukhov


2 Answers

This is known as "zipping" or "zip joining" two sequences. Eric Lippert describes this very algorithm and provides an implementation.

like image 179
Andrew Hare Avatar answered Dec 02 '22 08:12

Andrew Hare


The mighty Bart de Smet talks about zip functions here:

http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx

His most elegant solution takes advantage of an overload of select that takes a 2 parameter Func delegate as its parameter.

a.Select((t,i)=>new{t,i});

In this example, i simply represents the index of the item being processed. So you can create 2 new enumerables of these anonymous objects and join them on i.

Performance-wise, I'd go with a more obvious yielding loop.

like image 23
spender Avatar answered Dec 02 '22 10:12

spender