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"?
This is known as "zipping" or "zip joining" two sequences. Eric Lippert describes this very algorithm and provides an implementation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With