Is it possible to iterate over two IEnumerable objects at the same time?

前端 未结 7 1920
醉梦人生
醉梦人生 2020-12-19 12:55

If I have a List(Of x) and a List(Of y) is it possible to iterate over both at the same time?

Something like

for each _x as X, _y as Y in List(of x         


        
相关标签:
7条回答
  • 2020-12-19 13:44

    I'm not very proficient in VB.NET, but here's an extension method in C# you can create to do this. I hope you can port it!

    public static class IEnumExtensions
    {
        public static IEnumerable<KeyValuePair<T, U>> EnumTwoCollections<T, U>(this IEnumerable<T> list1, IEnumerable<U> list2)
        {
            var enumerator1 = list1.GetEnumerator();
            var enumerator2 = list2.GetEnumerator();
    
            bool moveNext1 = enumerator1.MoveNext();
            bool moveNext2 = enumerator2.MoveNext();
    
            while (moveNext1 || moveNext2)
            {
    
                T tItem = moveNext1 ? enumerator1.Current : default(T);
                U uItem = moveNext2 ? enumerator2.Current : default(U);
    
                yield return new KeyValuePair<T, U>(tItem, uItem);
    
                moveNext1 = enumerator1.MoveNext();
                moveNext2 = enumerator2.MoveNext();
            }
        }
    }
    

    Usage:

        List<int> intList = new List<int>();
        List<string> stringList = new List<string>();
        for (int i = 1; i <= 10; i++)
        {
            intList.Add(i);
            stringList.Add((i * i).ToString());
        }
    
        foreach (var items in intList.EnumTwoCollections(stringList))
        {
            Console.WriteLine(items.Key + " , " + items.Value);
        }
    

    Noticed now that you're not using .NET 3.5 so you probably can't use extension methods either. Just put this in some helper class and you can call it like this:

    foreach(KeyValuePair<int,string> kvp in Helper.EnumTwoCollections(intList,stringList))
    {
    ...
    }
    
    0 讨论(0)
提交回复
热议问题