Search code examples
c#sortedlist

SortedList and Linq


I'm confused after reading the documentation on what to expect when using Linq with a SortedList.

https://msdn.microsoft.com/en-us/library/ms132319(v=vs.110).aspx

I guess the enumeration is guaranteed to be sorted and also retrieve by index, but what about Values and Keys? Are all these cases safe?

        var list = new SortedList<DateTime, object>();

        //add entries here ...

        var firstValue1 = list.Values[0];
        var firstValue2 = list.First().Value;
        var firstValue3 = list.Values.First();

        var firstKey1 = list.Keys[list.Count-1];
        var firstKey2 = list.First().Key;
        var firstKey3 = list.Keys.First();

        var sortedList = list.Where(x => x.Key > DateTime.Now)
            .Select(x => x.Value);

Solution

  • Read the documentation...

    From the documentation on the Values property:

    "The order of the values in the IList<T> is the same as the order in the SortedList<TKey, TValue>."

    From the documentation on the Keys property:

    "The order of the keys in the IList<T> is the same as the order in the SortedList<TKey, TValue>."