How to filter a dictionary to have items with unique values?

Please carry me if you think that I have not done enough research before asking

Problem Just came across a business requirement in which we need to make sure that the values ​​in the dictionary are unique. those. we must filter the dictionary, and the result of such a filter should have pairs of key values ​​with unique values.

By the way, this is a simple Dictionary with string values ​​and string keys. To clarify in more detail, below are the sample values and the expected output values ​​-
sourceDictionary will have the meanings shown below (only for the presentation of data, not syntactically correct) - {{"Item1", "Item One"}, {"Item11", "Item One"}, {"Item2", "Second item "}, {" Item22 "," Item Two "}} for this input, filterDictionary should look like this: {{" Item1 "," Item One "}, {" Item2 "," Item Two "}}

The solution I proposed works

var sourceDictionary = serviceAgent.GetSampleDictionary(); // Simplified for brevity var filteredDictionary = sourceDictionary.GroupBy(s => s.Value) .Where(group => @group.Any()) .Select(g => g.First()) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); 

Question Am I doing too much logic in it? OR, in other words, is there an easier way to do this?

+6
source share
4 answers

This line:

 .Where(group => @group.Any()) 

not required since you will not receive any empty groups. (Also not sure what "@" is).

Other than this, there really is no simpler way to do this.

+6
source

Your method works, but it is not extremely readable. If you create your class this way:

 class DictionaryValueComparer<T1, T2> : IEqualityComparer<KeyValuePair<T1, T2>> { public bool Equals(KeyValuePair<T1, T2> x, KeyValuePair<T1, T2> y) { return x.Value.Equals(y.Value); } public int GetHashCode(KeyValuePair<T1, T2> obj) { return obj.Value.GetHashCode(); } } 

Then you can reduce your method to:

 dictionary = dictionary.Distinct(new DictionaryValueComparer<int, string>()). ToDictionary(p => p.Key, p => p.Value); 
+3
source

Why not use the Linq.Distinct () extension method?

0
source

Assuming this is not a custom type (then you need to implement IEqualityComparer<YourType> and pass it Distinct )

 var distinctDict = sourceDictionary .ToDictionary(kv => kv.Key, kv => kv.Value.Distinct()); 

Demo

 var sourceDictionary=new Dictionary<string, List<string>>(); sourceDictionary.Add("A", new List<string>() { "A", "A", "B"}); sourceDictionary.Add("B", new List<string>() { "C", "D", "D" }); var distinctDict = sourceDictionary.ToDictionary(kv => kv.Key, kv => kv.Value.Distinct()); foreach(var kv in distinctDict) Console.WriteLine("Key:{0} Values:{1}", kv.Key, string.Join(",", kv.Value)); // "A", "B" and "C", "D" 
0
source

All Articles