3

我怎样才能使这个 Distinct 工作:

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

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

4

2 回答 2

6
var blockIdMap = panelEntries.GroupBy(pe => pe.BlockNo)
            .ToDictionary(k => k.Key, v => v.First())
于 2012-07-11T11:30:58.797 回答
1

在这种情况下,您的 linq 查询不起作用,因为.Distinct()方法 equals panelEntry.BlockNoandpanelEntry.BlockID而 not only 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);
于 2012-07-11T11:48:50.230 回答