如何使用LINQ从列表中select提供的索引范围内的值

我是一个LINQ新手试图使用它来实现以下目标:

我有一个int列表:

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

现在,我想用LINQ来比较前三个元素[索引范围0-2]与最后三个[索引范围3-5]之和。 我尝试了LINQ Select和Take扩展方法以及SelectMany方法,但我无法弄清楚如何说

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

我也查看了Contains扩展方法,但是看不到我想要的。 有什么build议么? 谢谢。

使用跳过然后采取。

 yourEnumerable.Skip(4).Take(3).Select( x=>x ) (from p in intList.Skip(x).Take(n) select p).sum() 

你可以使用GetRange()

 list.GetRange(index, count); 

对于较大的列表,单独的扩展方法可能更适合于性能。 我知道这是不是最初的情况下,但Linq(对象)实现依赖迭代列表,所以对于大型列表,这可能是(毫无意义)昂贵。 一个简单的扩展方法来实现这一点可能是:

 public static IEnumerable<TSource> IndexRange<TSource>( this IList<TSource> source, int fromIndex, int toIndex) { int currIndex = fromIndex; while (currIndex <= toIndex) { yield return source[currIndex]; currIndex++; } }