Night Walker
Night Walker

Reputation: 21260

Distinct in Linq query

How I can make this Distinct work:

   var blockIdMap = (from panelEntry in panelEntries
                          select new {panelEntry.BlockNo, panelEntry.BlockID})
                          .Distinct()
                          .ToDictionary(mc => mc.BlockNo , mc => mc.BlockID);

I need to have only unique entries of BlockNo with it's BlockId because I enter them to Dictionary and BlockNo should be unique. I want just to take the first one.

Upvotes: 3

Views: 1548

Answers (2)

Omar
Omar

Reputation: 16623

In this case your linq query doesn't work beacuse .Distinct() method equals panelEntry.BlockNo and panelEntry.BlockID and not only panelEntry.BlockNo. So a solution could be use MoreLinq and the method .DistinctBy():

var blockIdMap = (from panelEntry in panelEntries
                 select new {panelEntry.BlockNo, panelEntry.BlockID})
                 .DistinctBy(mc => mc.BlockNo)
                 .ToDictionary(mc => mc.BlockNo , mc => mc.BlockID);

Upvotes: 1

Jamiec
Jamiec

Reputation: 136104

var blockIdMap = panelEntries.GroupBy(pe => pe.BlockNo)
            .ToDictionary(k => k.Key, v => v.First())

Upvotes: 6

Related Questions