The GetHashCode method in C# is not guaranteed to generate the same integer value for the same string or object across different executions of an application or even within the same execution. It is designed to generate a hash code quickly for use in hash-based data structures like dictionaries and sets, and it is based on the current state of the runtime environment.
In your case, you can use the JsonConvert.SerializeObject method to serialize the JsonKey object into a string, which can be used as the dictionary key. However, since the string representations of two JsonKey objects with the same values may not be the same due to differences in formatting or other factors, you should use the JsonConvert.SerializeObject method with the Formatting.None option to ensure consistent string representations.
Here's an updated version of your code that uses this approach to find the dictionary key corresponding to a JsonKey object:
private static void Find_Matching_Keys()
{
JsonKey key1 = new()
{
Index = 1,
ID = "A",
Name = "A",
Weight = 100,
};
JsonKey key2 = new()
{
Index = 1,
ID = "A",
Name = "B",
Weight = 200,
};
JsonKey key3 = new()
{
Index = 1,
ID = "A",
Name = "C",
Weight = 300,
};
Dictionary<string, int> dict = new()
{
{ JsonConvert.SerializeObject(key1, Formatting.None), 1 },
{ JsonConvert.SerializeObject(key2, Formatting.None), 2 },
{ JsonConvert.SerializeObject(key3, Formatting.None), 3 }
};
var look_key2 =
dict.Where(x => JsonConvert.SerializeObject(key2, Formatting.None) == x.Key).FirstOrDefault();
if (look_key2 != null)
{
Debug.Print($"Found key2 with value {look_key2.Value}");
}
else
{
Debug.Print("Not Found");
}
}