Typical context: I make an extension method for a collection which considers that the elements are ordered. The function starts at the beginning, at index 0, and the order has significance. Examples: Grouping by sequence or Indexes of an item.
However, I'm always stumped as to what to extend: IEnumerable<T>
or T[]
. My rationale was clarity of purpose: An array has a notion of ordering, whereas an IEnumerable is implemented by many generic collections, not all of which have a notion of order:
- Dictionary - unordered
- HashSet - unordered
- LinkedList - ordered
- List - ordered
- Queue - ordered
- SortedDictionary - sorted (not original order)
- SortedList - sorted (not original order)
- SortedSet - sorted (not original order)
- Stack - reversed
As well as any other implementation which might or might not be ordered.
Also, I'm not certain if the enumerator is reset if an enumeration is not completed, so if that's a worry, then who knows at what point the enumeration would start? Enumerating an array would always start at the beginning.
So to me, it makes more sense to extend a T[]
. But am I correct in thinking that? Am I worrying too much? What's the proper approach for ensuring "ordered" enumeration?