How to search dictionary key and find the value in C#?

john zyd 421 Reputation points
2023-01-24T20:34:08.8733333+00:00

Hello:

I have the following Json data stored into one dictionary:

        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 how to do this 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,238 questions
0 comments No comments
{count} votes