Get all remaining items with GetRange

3.2k views Asked by At

Recently, I've got interested in the List.GetRange() function. It can retrieve a sub-list from a bigger list. Usage requires two arguments:

List<T> SubList = List<T>.GetRange(10, 20) //Get 20 items, starting from index 10

But what if I wanted to take every remaining item from a specific index, with this function?

List<T> RemainingItemsFromList = MyList.GetRange(7, /*REST*/) //What can I insert into REST to make it retrieve everything?

Is there

  • Any built-in RestOfTheList statement without doing something like Length - Index?
  • Any replacement function (that already exists)?
  • Any other alternative?

or am I simply doing something wrong?

1

There are 1 answers

0
Evk On BEST ANSWER

Since List does not provide built-in method with required functionality, your options are:

1) Create extension method yourself:

public static class ListExtensions {
    public static List<T> GetRange<T>(this List<T> list, int start) {
        return list.GetRange(start, list.Count - start);
    }
}

var remaining = list.GetRange(7);

2) Use LINQ:

var remaining = list.Skip(7).ToList(); // a bit less efficient, but usually that does not matter