pencilCake pencilCake - 6 months ago 20
C# Question

Is there a built-in method to get the max index of a List<>?

Is there a built in method in C# to get the max index in a List ?


No, there isn't a built-in method. You can always use

int maxIndex = myList.Count - 1;

For a List, you are guaranteed that the elements will be in the range 0..Count-1, so you can create an extension method:

public static int LastIndex<T>(this List<T> list)
  return list.Count-1;

Off course, these lines will return -1 when the list has 0 elements, which might be a problem.