views:

917

answers:

4

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?

+4  A: 
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
}
Randolpho
This seems to be the closest to what JerryB might be intending to ask.
Steven Sudit
+1  A: 

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() )
{
}
LBushkin
Dictionary keys are already guaranteed distinct. No need for the LINQ call.
Reed Copsey
@Reed: Ok, but the LINQ is only being used to make values unique, not keys.
Steven Sudit
+3  A: 

Keys are distinct in a dictionary. By definition.

So myDict.Keys is a distinct list of keys.

Philippe Leybaert
but values are not.
Randolpho
Crap! I totally misread the question. I thought he wanted distinct values.
Randolpho
The question is a bit confusing. "distinct values of string keys" ?
Philippe Leybaert
JerryB asked "How do I get just the distinct values of string KEYS"
Meta-Knight
@Philippe Leybaert: I agree; a misleading question. I guess the author will have to show up and let us know what he really meant. Either way, +1 for your answer.
Randolpho
A: 

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();
Reed Copsey