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

后端 未结 4 769
北恋
北恋 2020-12-29 02:10

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

I have a list of ints:-

List intList = new List(new int[]{1,2,3,3         


        
4条回答
  •  有刺的猬
    2020-12-29 02:46

    For larger lists, a separate extension method could be more appropriate for performance. I know this isn't necessary for the initial case, but the Linq (to objects) implementation relies on iterating the list, so for large lists this could be (pointlessly) expensive. A simple extension method to achieve this could be:

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

提交回复
热议问题