如何使用LINQ从List中提供的索引范围内选择值

Pun*_*ora 62 c# linq list range

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

我有一份整体清单: -

List<int> intList = new List<int>(new int[]{1,2,3,3,2,1});
Run Code Online (Sandbox Code Playgroud)

现在,我想使用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()
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*lls 89

使用Skip然后Take.

yourEnumerable.Skip(4).Take(3).Select( x=>x )

(from p in intList.Skip(x).Take(n) select p).sum()
Run Code Online (Sandbox Code Playgroud)

  • 请注意,对于较大的集合,List <T> .GetRange将更有效:https://icodeit.wordpress.com/2012/08/27/performance-of-skip-and-take-in-linq-to-objects /,http://geekswithblogs.net/BlackRabbitCoder/archive/2012/03/29/c.net-little-wonders-skip-and-take.aspx (7认同)

Onu*_*alp 35

你可以使用GetRange()

list.GetRange(index, count);
Run Code Online (Sandbox Code Playgroud)

  • @AdamNofsinger这是在System.Collections.Generic命名空间下.它带有.Net 2.0.http://msdn.microsoft.com/en-us/library/21k0e39c(v=vs.80).aspx (4认同)

Tao*_*Tao 17

对于较大的列表,单独的扩展方法可能更适合于性能.我知道这对于初始情况不是必需的,但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++;
    }
}
Run Code Online (Sandbox Code Playgroud)