3

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.

Night Walker
  • 20,638
  • 52
  • 151
  • 228
  • You could always `GroupBy` `BlockNo` and then select `First` `BlockID`. The only way to change `Distinct` is with an `IEqualityComparer` or to use a class that implements `IEquatable` and overrides `GetHashCode`. You cannot do the former with anonymous types, and they have their own implementation for the latter that is locked. – Adam Houldsworth Jul 11 '12 at 11:31
  • @AdamHouldsworth - [The compiler overrides GetHashCode and Equals for anonymous types](http://stackoverflow.com/a/543591/219661) – Jamiec Jul 11 '12 at 11:34
  • @Jamiec I know, I amended my comment to state that you cannot change the implementation as my first draft was inaccurate. The default implementation will take all properties into account, not just the `BlockNo`. – Adam Houldsworth Jul 11 '12 at 11:35

2 Answers2

6
var blockIdMap = panelEntries.GroupBy(pe => pe.BlockNo)
            .ToDictionary(k => k.Key, v => v.First())
Jamiec
  • 133,658
  • 13
  • 134
  • 193
1

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);
Omar
  • 16,329
  • 10
  • 48
  • 66