Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select values within a provided index range from a List using LINQ

Tags:

c#

list

range

linq

I am a LINQ newbie trying to use it to acheive the following:

I have a list of ints:-

List<int> intList = new List<int>(new int[]{1,2,3,3,2,1}); 

Now, I want to compare the sum of the first three elements [index range 0-2] with the last three [index range 3-5] using LINQ. I tried the LINQ Select and Take extension methods as well as the SelectMany method, but I cannot figure out how to say something like

(from p in intList   where p in  Take contiguous elements of intList from index x to x+n   select p).sum() 

I looked at the Contains extension method too, but that doesn't see to get me what I want. Any suggestions? Thanks.

like image 492
Punit Vora Avatar asked Jun 25 '09 03:06

Punit Vora


People also ask

How do you find the index of an element in LINQ?

LINQ does not have an IndexOf method. So to find out index of a specific item we need to use FindIndex as int index = List. FindIndex(your condition); 0.

Can LINQ query work with array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.

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.


1 Answers

Use Skip then Take.

yourEnumerable.Skip(4).Take(3).Select( x=>x )  (from p in intList.Skip(x).Take(n) select p).sum() 
like image 190
Adam Sills Avatar answered Oct 09 '22 04:10

Adam Sills