Linqify: List Subset

Suppose I have a list or an array of elements, and I want to summarize a subset of the elements in a list. (in my case, it will always be a sequential subset).

Here is an old fashioned way:


int sum = 0;
for(int i = startIndex; i <= stopIndex; i++)
  sum += myList[i].TheValue;
return sum;

What is the best linqify way of this code?

+3
source share
1 answer
myList.Skip(startIndex).Take(stopIndex - startIndex + 1).Sum(x => x.TheValue);

If I did such things a lot, I would define an auxiliary TakeRangethat covered Skipand Takeso that I did not do it separately.

+6
source

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


All Articles