开发者

Linqify this: Aggregate a subset of a list

开发者 https://www.devze.com 2022-12-31 14:16 出处:网络
Suppose I have a list or array of items, and I want to sum a subset of the items in the list.(in my case, it happens to always be a sequential subset).

Suppose I have a list or array of items, and I want to sum a subset of the items in the list. (in my case, it happens to always be a sequential subset).

Here's the old-fashioned way:


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

What's the best w开发者_如何学运维ay to linqify that code?


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

If I were doing this sort of thing a lot, I'd define a helper TakeRange that covered the Skip and Take so that I didn't off-by-one it.

0

精彩评论

暂无评论...
验证码 换一张
取 消