Linq查询不同

时间:2012-07-11 11:28:32

标签: c# linq

我如何才能做出这种独特的工作:

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

我需要只有BlockNo的唯一条目和它的BlockId,因为我将它们输入到Dictionary并且BlockNo应该是唯一的。 我只想拿第一个。

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

在这种情况下,您的linq查询不起作用,因为.Distinct()方法等于panelEntry.BlockNopanelEntry.BlockID,而不仅仅是panelEntry.BlockNo。因此,解决方案可以使用MoreLinq和方法.DistinctBy()

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