2

I'm trying to get the last item in my ordered dictionary but it doesn't have the nice LINQ functions like a normal dictionary does such as .First() .Last()

I was just wondering if anyone knew how I could do this?

Mike Torrettinni
  • 1,816
  • 2
  • 17
  • 47
tize
  • 31
  • 1
  • Not sure why this is being down voted, It's a fair question. – tize Jan 21 '18 at 22:54
  • 2
    If you hover over the down arrow you will see the prompt “This question does not show any research effort”. Whether it's “fair” or not is irrelevant. – Dour High Arch Jan 21 '18 at 23:12
  • Possibly relevant or useful: [No generic implementation of OrderedDictionary?](https://stackoverflow.com/q/2629027). – dbc Jan 22 '18 at 00:16

1 Answers1

2

The System.Collections.Specialized.OrderedDictionary class does not implement the generic interface IEnumerable<>, and therefore the extension methods you mention do not apply.

You can use .Cast<DictionaryEntry>() first. It can be used because it is based on the non-generic IEnumerable interface. It returns a generic IEnumerable<DictionaryEntry>, so you can use .Last() on that.

But it may be better to use a "newer" collection type.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • How do I access the .Key and .Value on this? I only have .Values?? – tize Jan 21 '18 at 22:57
  • Never mind, after casting it as DictionaryEntry it worked. Thank you very much! – tize Jan 21 '18 at 22:58
  • Does casting to `DictionaryEntry` still guarantee sort order? – reubano May 11 '22 at 22:53
  • 1
    @reubano, Yes, it is guaranteed that `.Cast()` will yield the items (strongly typed as `TResult`) in exactly the same order as the `source` (i.e. the underlying instance of the nongeneric `IEnumerable` type) does. It does so _lazily_ (documentation "This method is implemented by using deferred execution"). If you look at the source code for `Cast()`, you see that the method is essentially a call to a private iterator method (i.e. a method whose body uses `yield return`) that looks like this: `{ foreach (object obj in source) yield return (TResult)obj; }` – Jeppe Stig Nielsen May 12 '22 at 08:05