How to use Json Data as dictionary key and find the value?

john zyd 421 Reputation points
2023-01-24T20:30:06.5233333+00:00
Hello:
I have the following Json data stored into one dictionary: (newtonsoft.json)
        public class JsonKey
        {
            public int? Index { get; set; }
            public string? ID { get; set; }
            public string? Name { get; set; }
            public double Weight { get; set; }
            public override string ToString()
            {
                return JsonConvert.SerializeObject(this);
            }
        }

        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()
            {
                { key1.ToString(), 1 },
                { key2.ToString(), 2 },
                { key3.ToString(), 3 }
            };
            var key2_hash = key2.GetHashCode();
            var keys =
                dict.Keys.Select(x => x.GetHashCode()).ToList();
            var look_key2 =
                dict.Where(x => x.Key.GetHashCode() == key2_hash).FirstOrDefault();
            Debug.Print("Not Found");
        }

I want to find one key from the dictionary and print out its value.  Since I have to use complex Json data as dictionary key to store some values in SQL server database.  Saving the Json format data into SQL server database is not difficult, but how to find which one is the one I want is not easy.
Using Json structure to directly compare the key is not working, serialize Json key into string and compare the string is not working. So I want to use GetHashCode to find the key.  As I think for the same string, the GetHashCode should generate the same integer value, but it seems not in C#.
Any suggestions on how to find Json format data from a dictionary?
Thanks,


C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,288 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Alan Farias 745 Reputation points
    2023-02-24T15:27:46.36+00:00

    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");
        }
    }
    
    
    0 comments No comments