Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

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 in future linq queries.

While I was able to do it using the code below, I can't help but feel like there must be a better way. Any ideas?

List<int> firstList = new List<int>(new int[] { 1, 3, 4, 2, 5, 7, 2, 5, 7, 8, 9, 0 });
List<int> secondList = new List<int>(new int[] { 4, 6, 8, 3, 1, 5, 9, 3, 0 });

int findex = 0;

ILookup<int, int> flookup = firstList.ToLookup(f =>
                            {
                               int i = findex;
                               findex++; 
                               return i;
                               }, p => p);  

var listsAdded = from grp in flookup
                 select grp.First() + secondList.ElementAtOrDefault(grp.Key);

foreach (int i in listsAdded)
  Console.WriteLine(i);
like image 246
Audie Avatar asked Mar 24 '10 22:03

Audie


People also ask

What is any () in Linq?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

How use all in Linq C#?

The Linq All Operator in C# is used to check whether all the elements of a data source satisfy a given condition or not. If all the elements satisfy the condition, then it returns true else return false. There is no overloaded version is available for the All method.


1 Answers

What you're looking for is a Zip method. This method allows you to combine to lists of equal length into a single list by applying a projection.

For example

var sumList = firstList.Zip(secondList, (x,y) => x + y).ToList();

This method was added to the BCL in CLR 4.0 (Reference). It's fairly straight forward to implement though and many versions are available online that can be copied into a 2.0 or 3.5 application.

like image 58
JaredPar Avatar answered Sep 30 '22 16:09

JaredPar