简体   繁体   中英

Best way to get range from 1 to n-1 with linq

I would like to use linq to query a sorted List with n elements, so that I can get elemnts between first and last.

I have tried the following, but it seems not to look good:

var result1 = myList.Skip(1).Take(myList.Count()-2);

var result2 = myList.GetRange(1, myList.Count()-2);

Are there other ways to achieve the goal?

You have to take into account that LinQ will perform as many loops as necessary to achieve its purpose. Sometimes, writing your own loop will gets better results. Then encapsulate your loop into an extension methods and you get your one line solution:

namespace System.Linq
{
    public static class MyLinqExtensions
    {
        public static IEnumerable<T> Range<T>(this IEnumerable<T> input, int start, int end)
        {               
            int i = 0;
            foreach(var item in input)
            {
                if(i < start) continue;
                if(i > end) break;

                yield return item;

                i++;
            }
        }
    }
}

This is Best Way

 var result1 = myList.Skip(1).Take(myList.Count()-2);

This Best way of Linq Query Because Getrange does not accept Negative Numer.

For Example: MyList is No record then Skip And Take method execute Linq query out put is empty list result but Getrange method throw exception for " Non-negative number required. Parameter name: count "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM