Please bear with me if you think I haven't done enough research before asking
Problem Just came across a business requirement where we have to make sure the values in a dictionary are unique. i.e., We should filter a dictionary and the result of such filtering should have key value pairs with unique values.
BTW, it is a simple Dictionary with string values and string keys. To clarify more, below are the sample input and expected output values -
sourceDictionary would have values like below (just for the sake of representation of data, not syntactically correct) - { {"Item1", "Item One"}, {"Item11", "Item One"}, {"Item2", "Item Two"}, {"Item22", "Item Two"} } for this input, filteredDictionary should look like below - { {"Item1", "Item One"}, {"Item2", "Item Two"} }
Solution I proposed that is working
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 making too much logic into it? OR, putting it in other words, is there a simpler way to do this?
This line:
.Where(group => @group.Any())
is unnecessary, as you won't get any empty groups anyway. (Also not sure what the '@' is for.)
Other than that, there's not really a simpler way to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With