Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Dictionary in C# Have a .Distinct() Extension?

Tags:

c#

dictionary

As the title says, why does the Dictionary collection in C# contain a .Distinct() extension as if it's possible for a Dictionary to contain non-distinct keys? Is there legitimate reasoning behind this or am I reading too far into it?

like image 304
DanteTheEgregore Avatar asked Nov 23 '25 08:11

DanteTheEgregore


2 Answers

Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>> which has a Distinct extension. The Dictionary class itself doesn't have an implementation of Distinct

Calling the Distinct is translated to a call to the static extension method:

Enueramble.Distinct(IEnumerable<T> source)

Which is unneccesary for Dictionary since keys are distinct (and hence key/value pairs are distinct) but technically there's nothing wrong with it.

like image 58
D Stanley Avatar answered Nov 26 '25 16:11

D Stanley


The Distinct applies to the IEnumerable<KeyValuePair<TKey, TValue>> interface from a Dictionary<TKey, TValue>. While it doesn't make sense because a dictionary have unique keys, the extension will be present solely because Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>.

like image 20
Simon Belanger Avatar answered Nov 26 '25 18:11

Simon Belanger