Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through 2 lists at once

Tags:

I have two lists that are of the same length, is it possible to loop through these two lists at once?

I am looking for the correct syntax to do the below

foreach itemA, itemB in ListA, ListB {   Console.WriteLine(itemA.ToString()+","+itemB.ToString()); } 

do you think this is possible in C#? And if it is, what is the lambda expression equivalent of this?

like image 617
Graviton Avatar asked Oct 28 '08 06:10

Graviton


2 Answers

[edit]: to clarify; this is useful in the generic LINQ / IEnumerable<T> context, where you can't use an indexer, because a: it doesn't exist on an enumerable, and b: you can't guarantee that you can read the data more than once. Since the OP mentions lambdas, it occurs that LINQ might not be too far away (and yes, I do realise that LINQ and lambdas are not quite the same thing).

It sounds like you need the missing Zip operator; you can spoof it:

static void Main() {     int[] left = { 1, 2, 3, 4, 5 };     string[] right = { "abc", "def", "ghi", "jkl", "mno" };      // using KeyValuePair<,> approach     foreach (var item in left.Zip(right))     {         Console.WriteLine("{0}/{1}", item.Key, item.Value);     }      // using projection approach     foreach (string item in left.Zip(right,         (x,y) => string.Format("{0}/{1}", x, y)))     {         Console.WriteLine(item);     } }  // library code; written once and stuffed away in a util assembly...  // returns each pais as a KeyValuePair<,> static IEnumerable<KeyValuePair<TLeft,TRight>> Zip<TLeft, TRight>(     this IEnumerable<TLeft> left, IEnumerable<TRight> right) {     return Zip(left, right, (x, y) => new KeyValuePair<TLeft, TRight>(x, y)); }  // accepts a projection from the caller for each pair static IEnumerable<TResult> Zip<TLeft, TRight, TResult>(     this IEnumerable<TLeft> left, IEnumerable<TRight> right,     Func<TLeft, TRight, TResult> selector) {     using(IEnumerator<TLeft> leftE = left.GetEnumerator())     using (IEnumerator<TRight> rightE = right.GetEnumerator())     {         while (leftE.MoveNext() && rightE.MoveNext())         {             yield return selector(leftE.Current, rightE.Current);         }     } } 
like image 145
Marc Gravell Avatar answered Sep 21 '22 19:09

Marc Gravell


It'll be much simpler to just do it in a plain old for loop instead...

for(int i=0; i<ListA.Length; i++) {     Console.WriteLine(ListA[i].ToString() + ", " + ListB[i].ToString()); } 
like image 31
jcelgin Avatar answered Sep 21 '22 19:09

jcelgin