Search code examples
c#collectionsrankcontractpreserve

Is it possible to provide an ordering guarantee for a collection?


I'm trying to create a method which (other than in name) shows that the ordering of some collection will be preserved.

I have considered SortedList, but dismissed it due to the requirement of holding a key. I have also dismissed other Sorted types for similar reasons, and SortedSet due to Linq returning IEnumerable instead of another SortedSet when you operate on it.

I don't mind if a new type is required, or I need to write methods in a specific way. The goal here is to highlight methods which preserve the input order of a collection when operating upon it.

I had thought about adding a custom attribute and just trusting that it will be used correctly, but I would ideally like to find something in the language which is more explicit.

-- Edit

It's not so much the order of the elements in the collection (I could use an IEnumerable), but some operation on the input collection. Let's say I were returning the root of all the numbers in an array, instead of returning (root, number)[], or (root, index)[] I want to return root[] and have it clear to the user that the order of the elements in the returned array matches the order of the elements in the input parameter.


Solution

  • No, there is nothing in C# or .Net that let you express and enforce "this method does not change order of elements in a collection / while iterating through collection".

    Conventional expectation is order of elements stored in a collection preserved while iterating unless method/class explicitly named to indicate reordering.

    Examples of "no reordering":

    • for / 'foreach`
    • .Select, .First, .Take, .SelectMany, .Where
    • indexing of collection that is not called "SortedXxxxx" - List, array.

    Examples of "does reordering"

    • List.Sort, List.Reverse
    • .OrderBy, .ThenBy
    • classes that don't preserve/guarantee ordering like HashSet, Dictionary, OrderedDictionary, SortedList