Linq - How to add content from two lists

I have two IEnumberable<double> lists.

How can I add each value of one list to a value at the same position in another list using Linq?

+4
source share
4 answers

You can use Enumerable.Zip to do this:

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

Please note that if the lists do not have the same length, your results will be the length of the shorter of the two lists ( Zip , as described above, will add elements until one sequence ends and then stops ...)

+6
source

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

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

with .NET 4 - you can use ZIP

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

Here you can find the .NET 3.5 implementation

+2
source

If you want your output to contain all the elements (or to feel what will happen under the Linq covers), you can flip your own Zip overload like this:

 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; } } } 
0
source

Source: https://habr.com/ru/post/1383465/


All Articles