Search code examples
c#linqdictionarylambdadistinct

Linq get Distinct ToDictionary


need help to only select/get distinct entries based on i.Code. There are duplicates and thus I'm getting an error in my expression "An item with the same key has already been added."

 var myDictionary = dbContext.myDbTable
            .Where(i => i.shoesize>= 4)
            .OrderBy(i => i.Code)              
            .ToDictionary(i => i.Code, i => i);

Have tried to use Select and/or Distinct in different combinations and also by themselves but am still getting the same error

var myDictionary= dbContext.myDbTable
            .Where(i => i.shoesize>= 4)
            .OrderBy(i => i.Code)
            //.Select(i => i)
            //.Distinct()
            .ToDictionary(i => i.Code, i => i);

Can anybody help? C#

UPDATE: If there are multiple objects with the same code I only want to add the first object(with that particular code) to myDictionary.


Solution

  • By dividing it and creating a list first it worked as compared to when it was all bundled up into one linq, guess the First() needed it to be in a list before being able to make it into a dict.

    var firstLinq = dbContext.myDbTable
               .Where(i => i.shoesize>= 4)
               .ToList();
    

    then

     var finalLinq = fromConcurWithDuplicates
                .GroupBy(i => i.Code)
                .Select(i => i.First())
                .ToList()
                .ToDictionary(i => i.Code, i => i);