JerryB
JerryB

Reputation:

Distinct Values in Dictionary<TKey,TValue>

I'm trying to loop over distinct values over a dictionary list:

So I have a dictionary of key value pairs .

How do I get just the distinct values of string keys from the dictionary list?

Upvotes: 12

Views: 58397

Answers (4)

Randolpho
Randolpho

Reputation: 56391

var distinctList = mydict.Values.Distinct().ToList();

Alternatively, you don't need to call ToList():

foreach(var value in mydict.Values.Distinct())
{
  // deal with it. 
}

Edit: I misread your question and thought you wanted distinct values from the dictionary. The above code provides that.

Keys are automatically distinct. So just use

foreach(var key in mydict.Keys)
{
  // deal with it
}

Upvotes: 43

Reed Copsey
Reed Copsey

Reputation: 564413

If the dictionary is defined as:

Dictionary<string,MyType> theDictionary =  ...

Then you can just use

var distinctKeys = theDictionary.Keys;

This uses the Dictionary.Keys property. If you need a list, you can use:

var dictionaryKeysAsList = theDictionary.Keys.ToList();

Since it's a dictionary, the keys will already be distinct.

If you're trying to find all of the distinct values (as opposed to keys - it wasn't clear in the question) in the dictionary, you could use:

var distinctDictionaryValues = theDictionary.Values.Distinct(); // .ToList();

Upvotes: 0

Philippe Leybaert
Philippe Leybaert

Reputation: 171784

Keys are distinct in a dictionary. By definition.

So myDict.Keys is a distinct list of keys.

Upvotes: 11

LBushkin
LBushkin

Reputation: 131676

Looping over distinct keys and doing something with each value...

foreach( dictionary.Keys )
{
    // your code
}

If you're using C# 3.0 and have access to LINQ:

Just fetching the set of distinct values:

// you may need to pass Distinct an IEqualityComparer<TSource>
// if default equality semantics are not appropriate...
foreach( dictionary.Values.Distinct() )
{
}

Upvotes: 2

Related Questions