I need to make a custom class as key in my dictionary. Which method is used by C# to do hashing when key is string?
internal class Patient:IEquatable<Patient>
{
public string fname{ get; set; }
public string lname{ get; set; }
public override int GetHashCode()
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(fname+lname);
}
}
Is this the correct approach (concatenation and generating hash), or is their any better way to generate hash.
Since .NET Core 2.1 you can use HashCode.Combine
:
return HashCode.Combine(fname, lname);
Or for case insensitive version:
return HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(fname),
StringComparer.OrdinalIgnoreCase.GetHashCode(fname));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.