How do I merge (or zip) two IEnumerables together?

前端 未结 10 1571
予麋鹿
予麋鹿 2020-12-17 00:38

I have an IEnumerable and an IEnumerable that I want merged into an IEnumerable> where

10条回答
  •  囚心锁ツ
    2020-12-17 00:47

    I would use something along the lines of -

    IEnumerable> Merge(IEnumerable keyCollection, IEnumerable valueCollection)
    {
        var keys = keyCollection.GetEnumerator();
        var values = valueCollection.GetEnumerator();
        try
        { 
            keys.Reset();
            values.Reset();
    
            while (keys.MoveNext() && values.MoveNext())
            {
                yield return new KeyValuePair(keys.Current,values.Current);
            }
        }
        finally
        {
            keys.Dispose();
            values.Dispose();
        }
    }
    

    This should work correctly, and cleanup properly afterwards.

提交回复
热议问题