我是一个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()
我也查看了包含扩展方法,但这并不能得到我想要的结果。有什么建议吗?谢谢。
发布于 2009-06-25 03:54:25
使用Skip,然后使用Take。
yourEnumerable.Skip(4).Take(3).Select( x=>x )
(from p in intList.Skip(x).Take(n) select p).sum()
发布于 2013-07-10 19:11:17
您可以使用GetRange()
list.GetRange(index, count);
发布于 2011-06-06 05:07:04
对于较大的列表,单独的扩展方法可能更适合于性能。我知道这对于最初的情况不是必需的,但是Linq (to objects)实现依赖于迭代列表,所以对于大的列表,这可能是(毫无意义的)昂贵的。实现这一点的简单扩展方法可以是:
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++;
}
}
https://stackoverflow.com/questions/1042087
复制相似问题