Home > Mobile >  Linq get Distinct ToDictionary
Linq get Distinct ToDictionary

Time:03-01

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#

CodePudding user response:

You can group by Code and select the first item from each group (which is equivalent to distinct):

var myDictionary = dbContext.myDbTable
            .Where(i => i.shoesize >= 4)      // filter
            .GroupBy(x => x.Code)             // group by Code
            .Select(g => g.First())           // select 1st item from each group           
            .ToDictionary(i => i.Code, i => i);

You don't need the OrderBy since Dictionarys represent an unordered collection. If you need an ordered dictionary you could use SortedDictionary.

CodePudding user response:

You could use a dictionary, then use GroupBy as haldo has shown in his answer. But since you haven't clarified what item you want to take in case of duplicates, i suggest you a different aproach using ToLookup. It has the same lookup performance as a dictionary but allows duplicate keys:

var codeLookup = dbContext.myDbTable
    .Where(i => i.shoesize>= 4)
    .ToLookup(i => i.Code);

You always get a IEnumerable<T> if you access the lookup, because there could be 0, 1 or multiple items. So you also don't get an exception if you ask for a code that is not contained.

  • Related