2

Dictionary<TKey, TValue>.KeyCollection Class implements the contains through extension method from IEnumerable, which is O(n)

why doesn't it have a native one with O(1)? it's kind of HashSet isn't it?

colinfang
  • 20,909
  • 19
  • 90
  • 173
  • Related: https://stackoverflow.com/questions/8235840/dictionary-keys-contains-vs-containskey-are-they-functionally-equivalent – nawfal May 18 '18 at 05:20

1 Answers1

6

It does implement its own Contains. You can't implement an interface through an extension method. Note that it implements it explicitly, which means you first have to cast it to ICollection to use it.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
  • 3
    Also, `Enumerable.Contains` checks if its parameter implements `ICollection`, so the operation is O(1) even if you call it via the extension method. That is, `dict.Keys.Contains` is just as fast as `dict.ContainsKey` (ignoring the creation of the `KeyCollection` object itself, which is trivial anyway). – Bradley Grainger Aug 27 '11 at 00:37
  • my bad, didn't see the explicit methods part in MSDN – colinfang Aug 27 '11 at 00:40