C # ToDictionary with ContainsKey check

I have a list that I want to put in the dictionary, for simplicity, the inserted values ​​will be the same.

I can use the foreach loop.

List<string> list = new List<string>(); list.Add("Earth"); list.Add("Wind"); list.Add("Fire"); list.Add("Water"); list.Add("Water"); // Will NOT BE INSERTED using the foreach loop var myDictionary= new Dictionary<string, int>(); foreach (string value in list) { if (!myDictionary.ContainsKey(value)) { myDictionary.Add(value, 1); } } 

The above work.

But I want to use ToDictionary to do the same as follows -

  Dictionary<string, int> myDictionary2 = list.ToDictionary(i => i, i => 1); 

Of course, this fails because I add Water twice.

What is the correct way to check for duplicate entries when using ToDictionary?

+7
source share
2 answers

You can use Distinct() to filter duplicates:

 Dictionary<string, int> myDictionary2 = list.Distinct().ToDictionary(i => i, i => 1); 

The same approach will make your traditional loop much clearer, since you do not need to check "manually" for duplicates:

 foreach (string value in list.Distinct()) { myDictionary.Add(value, 1); } 
+14
source

Distinct is one option that avoids duplication of a key problem. If you need the number of duplicates, you can try something more similar to this GroupBy as follows:

 var dict = list.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count()); 

If your application is not just a simple row / duplicate list structure, you can get some mileage from choosing another structure, such as Lookup , which you can get from calling the ToLookup extension or perhaps with a Grouping like GroupBy that I used above.

+7
source

All Articles