theHaggis
theHaggis

Reputation: 645

Linq - How can a add the contents of two list

I have two IEnumberable<double> list.

How can i add the each value of one list to the value in the same position in the other list using Linq?

Upvotes: 4

Views: 167

Answers (4)

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

If you wish to have your output contain all elements (or get a feel for what will be going on under the covers of Linq) you can roll your own overload of Zip like so:

public static IEnumerable<T> Zip<T>(IEnumerable<T> first, IEnumerable<T> second, Func<T,T,T> aggregator)
{
    using (var firstEnumerator = first.GetEnumerator())
    using (var secondEnumerator = second.GetEnumerator())
    {
        var movedFirstButNotSecond = false;
        while ((movedFirstButNotSecond = firstEnumerator.MoveNext()) && secondEnumerator.MoveNext())
        {
            yield return aggregator(firstEnumerator.Current, secondEnumerator.Current);
            movedFirstButNotSecond = false;                
        }
        while (movedFirstButNotSecond || firstEnumerator.MoveNext())
        {
            yield return firstEnumerator.Current;
            movedFirstButNotSecond = false;
        }
        while (secondEnumerator.MoveNext())
        {
            yield return secondEnumerator.Current;
        }
    }
}

Upvotes: 0

Arnon Rotem-Gal-Oz
Arnon Rotem-Gal-Oz

Reputation: 25909

with .NET 4 - you can use ZIP

var sumList = numbers2.Zip(numbers,
    (first, second) => first+second);

You can find a .NET 3.5 implementation here

Upvotes: 2

Austin Salonen
Austin Salonen

Reputation: 50225

Assuming both are the same length, you can use Zip and not lose anything. If they are of different lengths, the shortest list length will be the resulting length.

first.Zip(second, (a,b) => a+b);

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564423

You can use Enumerable.Zip to do this:

var results = first.Zip(second, (f,s) => f+s);

Note that, if the lists aren't the same length, your results will be the length of the shorter of the two lists (Zip as written above will add together elements until one sequence ends, then stop...)

Upvotes: 6

Related Questions