I have a custom object (DataPoin开发者_如何学CtCollection) 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).
You need to override both GetHashCode and Equals - it's the combination of the two which will be used by the HashSet.
Your equality check should:
- Check that the other object is of the same type as this object (it's simpler if DataPointCollectionis a sealed type; equality and inheritance are messy when combined)
- Compare the three fields for equality
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):
public override int GetHashCode()
{
    int hash = 17;
    hash = hash * 31 + projectId;
    hash = hash * 31 + roleId;
    hash = hash * 31 + resourceGuid.GetHashCode();
    return hash;
}
If I understand you correctly, you just need to override the GetHashCode and Equals methods in your DataPointCollection class, and use the method in this question to generate the hash code.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论