我想使用VB.Net在列表上分组。看似简单,但我不能让它工作。我试过了:
Dim groupedEmails = saEmails.GroupBy(Function(m) New With {m.Property1, m.Property2, m.Property3.SubProperty1})
我在saEmails中有6个项目,其中两个项目具有相同的Property1,Property2和Property3。不幸的是,在运行时我仍然在分组电子邮件中获得6个项目,即使我的分组应该将该计数减少到5个。
我已经尝试过没有“New With”的语句(它仍然编译),但结果是一样的。我也无法让Linq to Entities(“来自saEmails中的邮件......”)接受我对关键字“Group”的使用。我有导入 ed System.Linq。
我也很高兴使用.ToLookup()。
实体与此类似:
Namespace Something
<DataContract()>
Public Class SAEmail
<DataMember()>
Public Property Property1 As Integer
<DataMember()>
Public Property Property2 As String
<DataMember()>
Public Property Property3 As Blah
<DataMember()>
Public Property Property4 As String
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing OrElse Not Me.GetType() Is obj.GetType() Then
Return False
End If
Dim email As SAEmail = CType(obj, SAEmail)
Return Property1 = email.Property1 _
AndAlso Property2 = email.Property2 _
AndAlso Property1.SubProperty1 = email.Property3.SubProperty1
End Function
Public Overrides Function GetHashCode() As Integer
Return CInt(CLng(Property1) Xor CLng(Property2) Xor CLng(Property3.SubProperty1))
End Function
End Class
<DataContract()>
Public Class Blah
<DataMember()>
Public Property SubProperty1 As Integer
<DataMember()>
Public Property SubProperty2 As String
End Class
End Namespace
想法?
答案 0 :(得分:1)
如何创建复合分组键?
Dim groupedEmails = saEmails.GroupBy(Function(m) String.Format("{0}:{1}:{2}", m.Property1, m.Property2, m.Property3.SubProperty1))
或者,在几周内发布VB14时使用插值字符串!:
Dim groupedEmails = saEmails.GroupBy(Function(m) $"{m.Property1}:{m.Property2}:{m.Property3.SubProperty1)}")