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?
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?
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
}
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() )
{
}
Keys are distinct in a dictionary. By definition.
So myDict.Keys is a distinct list of keys.
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();