简体   繁体   中英

c# ToDictionary with ContainsKey check

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?

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM