How do I add two lists in Linq so addedList[x] = listOne[x] + listTwo[x]?

前端 未结 4 1684
我寻月下人不归
我寻月下人不归 2021-01-05 02:43

I want to add two lists of a numeric type such that addedList[x] = listOne[x] + listTwo[x]

The output of the list needs to be a Generic.IEnumerable that I can use i

4条回答
  •  囚心锁ツ
    2021-01-05 03:31

    It sounds like you want a function like this:

    public static IEnumerable SumIntLists( 
        this IEnumerable first, 
        IEnumerable second) 
    {
        using(var enumeratorA = first.GetEnumerator()) 
        using(var enumeratorB = second.GetEnumerator()) 
        { 
            while (enumeratorA.MoveNext()) 
            {
                if (enumeratorB.MoveNext())
                    yield return enumeratorA.Current + enumeratorB.Current;
                else
                    yield return enumeratorA.Current;
            }
            // should it continue iterating the second list?
            while (enumeratorB.MoveNext())
                yield return enumeratorB.Current;
        } 
    } 
    

提交回复
热议问题