Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

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?

like image 921
Thimmu Lanka Avatar asked Jan 03 '13 12:01

Thimmu Lanka


1 Answers

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.

like image 93
Rawling Avatar answered Oct 29 '22 17:10

Rawling