Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a unique hash code based on some properties of an object [duplicate]

Tags:

c#

compare

hash

I have to following classes:

public class NominalValue
{
   public int Id {get; set;}
   public string ElementName {get; set;}
   public decimal From {get; set;}  
   public decimal To {get; set;}    
   public bool Enable {get; set;}   
   public DateTime CreationDate {get; set;}
   public int StandardValueId {get; set;}  //FK for StandardValue
} 
public class StandardValue
{
   public int Id {get; set;}
   public string ElementName {get; set;}
   public decimal From {get; set;}  
   public decimal To {get; set;}    
   public bool Enable {get; set;}   
   public DateTime CreationDate {get; set;}
} 

User wants to fill nominalValue object properties. filling the nominalValue properties can performed in 2 way:

  1. User fill values for nominalValue manually.
  2. User Load values for nominalValue from a standardValue object and then change some values or not.

sometimes I need to know if some property of nominalValue objects for a specified Element are equal to corresponding standardValue or not?

I don't want to load standardValue from Db for checking this equality, so I decided to define a HashValue property in NominalValue class:

public class NominalValue
{
   public int Id {get; set;}
   public string ElementName {get; set;}
   public decimal From {get; set;}  //<-- 1st parameter for generating hash value
   public decimal To {get; set;}    //<-- 2nd parameter for generating hash value
   public bool Enable {get; set;}   //<-- 3rd parameter for generating hash value 
   public DateTime CreationDate {get; set;}
   public int StandardValueId {get; set;}  
   public string HashValue {get;set;}      //<-- this property added
} 

when user fill nominalValue properties using standardValue properties, I calculate its value based on 3 properties(From, To, Enable) and save it with other properties, and when I check if that nominalValue fill with standardValue or not, I calculate hash code for From, To, Enable and compare the result with HashValue (instead loading standardValue from Db).

Is there any mechanism to calculate a unique hash code based on 3 property values(From, To, Enable)?

like image 665
Masoud Avatar asked Oct 18 '22 18:10

Masoud


1 Answers

You can try to do something like this :

private int GetHashValue() {
    unchecked 
    {
        int hash = 17;
        //dont forget nullity checks 
        hash = hash * 23 + From.GetHashCode();
        hash = hash * 23 + To.GetHashCode();
        hash = hash * 23 + Enable.GetHashCode();
        return hash;
    }
}

You can use the GetHashCode method on an anonymous type too

private int GetHashValue() {
   return new { From, To, Enable }.GetHashCode();
}
like image 191
Quentin Roger Avatar answered Oct 27 '22 08:10

Quentin Roger