生成对象的哈希码
我有一个自定义对象 (DataPointCollection
),它具有两个 Integer 属性和一个 Guid 属性。我希望该对象生成一个 HashCode,以便不会将这些属性中具有相同值的两个对象添加到 HashSet 中。我知道我需要重写 GetHashCode()
方法,但是如何生成哈希码来完成此操作?
这是我想如何使用它。
Dim dataPointCollections As New HashSet(Of DataPointCollection)()
For Each row As DataRow In myDataSet.Tables(0).Rows
Dim dataPointCollection As New DataPointCollection()
dataPointCollection.ProjectID = row("ProjectID") 'Integer'
dataPointCollection.RoleID = row("RoleID") 'Integer'
dataPointCollection.ResourceGUID = row("ResourceGUID") 'Guid'
If Not dataPointCollections.Contains(dataPointCollection) Then
dataPointCollections.Add(dataPointCollection)
End If
Next
我对其他想法持开放态度,但我认为这可能比对对象集合(可能有大量这些对象)执行 LINQ 查询更快。
I have a custom object (DataPointCollection
) with two Integer properties and a Guid property. I want that object to generate a HashCode so that no two objects with the same values in those properties are added to a HashSet. I know I need to override the GetHashCode()
method, but how do I do generate a hash code to accomplish this?
Here's how I want to use it.
Dim dataPointCollections As New HashSet(Of DataPointCollection)()
For Each row As DataRow In myDataSet.Tables(0).Rows
Dim dataPointCollection As New DataPointCollection()
dataPointCollection.ProjectID = row("ProjectID") 'Integer'
dataPointCollection.RoleID = row("RoleID") 'Integer'
dataPointCollection.ResourceGUID = row("ResourceGUID") 'Guid'
If Not dataPointCollections.Contains(dataPointCollection) Then
dataPointCollections.Add(dataPointCollection)
End If
Next
I'm open to other ideas, but I thought this might be faster than doing a LINQ query on a collection of objects (there could be a very large number of these objects).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要重写
GetHashCode
和Equals
- 它是HashSet
将使用的两者的组合。您的相等性检查应该:
DataPointCollection
是密封类型,则更简单;相等性和继承在组合时会很混乱)性哈希码检查需要结合三个字段;结果不必必须是唯一的;对于性能来说,如果两个不相等的对象具有不同的哈希码,则更好,但这不是必需的。绝对要求是两个相等的对象确实具有相同的哈希码。我会做这样的事情(C#,但很容易转换为 VB):
You need to override both
GetHashCode
andEquals
- it's the combination of the two which will be used by theHashSet
.Your equality check should:
DataPointCollection
is a sealed type; equality and inheritance are messy when combined)Your hash code check needs to combine the three fields; the result doesn't have to be unique; for performance it's better if two unequal objects have a different hash code, but that's not required. The absolute requirement is that two equal objects do have the same hash code. I'd do something like this (C#, but easy to convert to VB):
如果我理解正确的话,您只需重写
DataPointCollection
类中的GetHashCode
和Equals
方法,并使用 这个问题生成哈希码。If I understand you correctly, you just need to override the
GetHashCode
andEquals
methods in yourDataPointCollection
class, and use the method in this question to generate the hash code.