c# ToDictionary with ContainsKey check

10,035

Solution 1

You could use Distinct() to filter out duplicates:

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

The same approach would make your traditional loop much clearer too, since you don't have to check "manually" for duplicates:

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

Solution 2

Distinct is one option that avoids the duplicate key issue. If you need a count of duplicates, you might try something more like 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 string-list/duplicate-count structure, you might get some mileage from choosing a different structure like a Lookup that you can get from calling the ToLookup extension -or possibly going with a Grouping like the GroupBy I used above.

Share:
10,035
Bryan
Author by

Bryan

Updated on July 28, 2022

Comments

  • Bryan
    Bryan over 1 year

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

    I can use a 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 works.

    But I want to use ToDictionary do the same in the following way -

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

    Of course this fails because I'm adding "Water" twice.

    What is the correct way of checking for duplicate entries when using ToDictionary?