Looping through 2 Lists at once

前端 未结 7 437

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



        
7条回答
  •  醉梦人生
    2021-01-31 11:05

    [edit]: to clarify; this is useful in the generic LINQ / IEnumerable 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> Zip(
        this IEnumerable left, IEnumerable right)
    {
        return Zip(left, right, (x, y) => new KeyValuePair(x, y));
    }
    
    // accepts a projection from the caller for each pair
    static IEnumerable Zip(
        this IEnumerable left, IEnumerable right,
        Func selector)
    {
        using(IEnumerator leftE = left.GetEnumerator())
        using (IEnumerator rightE = right.GetEnumerator())
        {
            while (leftE.MoveNext() && rightE.MoveNext())
            {
                yield return selector(leftE.Current, rightE.Current);
            }
        }
    }
    

提交回复
热议问题