Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 985
Bryan Avatar asked Mar 29 '12 18:03

Bryan


1 Answers

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);
}
like image 176
BrokenGlass Avatar answered Sep 19 '22 08:09

BrokenGlass