使用非键控值在LINQ中按匿名类型进行分组

时间:2015-10-21 17:20:15

标签: vb.net linq

我尝试对LINQ查询进行分组以查找重复值。根据MSDN,如果我将属性指定为非键控,则在评估表达式时应忽略它们:

来自MSDN:

https://msdn.microsoft.com/en-us/library/bb384767.aspx

Dim prod7 = New With {Key .Name = "paperclips", Key .Price = 1.29,
                  .OnHand = 24}
Dim prod8 = New With {Key .Name = "paperclips", Key .Price = 1.29,
                  .OnHand = 423}
' The following line displays True, because prod7 and prod8 are
' instances of the same anonymous type, and the values of their
' key properties are equal. The equality check does not compare the
' values of the non-key field.

我的代码:

 Dim query = people.GroupBy(Function(i) New With
 {Key i.EmailAddress, Key i.LastName, Key i.FirstName, i.ID}).
 Where(Function(g) g.Count() > 1).ToList()

我希望代码返回一些结果,它返回零。如果我删除i.ID我得到预期的结果数量。

1 个答案:

答案 0 :(得分:0)

简单的答案是LINQ的GroupBy函数不使用键控属性。那就是说,这就是我相信你在寻找的东西:

Dim query = people.GroupBy(Function(i) New With
 {i.EmailAddress, i.LastName, i.FirstName}, Function(i) New With { i.ID}).
 Where(Function(g) g.Count() > 1).ToList()

此版本的GroupBy已将Keyed属性和非键控属性分离为单独的lambda函数。

事实上,我甚至可以说完全忘记了Key属性。我从来没有真正看到它们被使用过,MSDN文章中描述的实现将非常直观。 某些属性相等的两个实体被视为相等是非常奇怪的行为。

相关问题