pencilCake pencilCake - 1 year ago 57
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 ?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download