Home > other >  Why can't I access a specific Key within my Dictionary in C#?
Why can't I access a specific Key within my Dictionary in C#?

Time:09-24

I've tried breaking this down as best I can.

Here is the relevant code with my best explanation of what each line does.

public static string DetailCall()
        {
            //Call original API POST Method to get Data
            string data = BlocCall();
            //Clean Data by removing extra characters
            var charsToRemove = new string[] { "{", "\"", " "};
            foreach (var c in charsToRemove)
            {
                data = data.Replace(c, string.Empty);
            }

            //Split string of data into an array of data by individual
            string[] guys = data.Split('}');
            
            //Do stuff with each persons data
            foreach (var individual in guys)
            {   
                //Split Data into key value pairs and add to Dictionary
                var uDict = individual.Split(',').Select(part => part.Split(':')).Where(part => part.Length == 2).ToDictionary(sp => sp[0], sp => sp[1]);

                //Turn the Dictionary back into a string for testing purposes
                var s_uDict = String.Join(",", uDict.Select(kvp => String.Format("{0}={1}", kvp.Key, kvp.Value)));

     
                Trace.WriteLine(s_uDict);

                Trace.WriteLine("Exist key "   uDict.ContainsKey("INDIVIDUALID"));     

            }
         }

I've used Trace.WriteLine to do some debugging and this is the (changed for hippa reasons) output in the console. It shows the contents of the dictionary as a string and I can clearly see which keys and values exist.

individualID=-----,
firstName=------,
middleInitial=,
lastName=------,
[email protected],
ssn=,
status=01.FreshLead,
type=,
homePhone=(---)--------,
businessPhone=,
cellPhone=

Exist key False

But whenever I try to access the data using

var cliID = uDict["individualID"];

I get the error that the Key "individualID" does not exist even though I can see in the output that it does??

I've also tried with the other key values and get the same result.

I'm pretty stumped at this point, and hope anyone can help me figure this out.

Thanks for your time.

CodePudding user response:

Your dictionary contains:

individualID=-----,

Your lookup that attempt seems to be:

Trace.WriteLine("Exist key " uDict.ContainsKey("INDIVIDUALID"));

Exist key False

"INDIVIDUALID" will have a completely different hashcode to "individualID"; in short - dictionary keys are case sensitive

Elsewhere in the post you indicated that you're looking up uDict["individualID"] which is correctly cased; if you're truly getting that I'd hazard a guess that it isn't the uDict you think it is e.g. you've got a clas level uDict variable and a local one named the same and you're getting them confused, etc

I had a go at reconstructing your input string and the code appears fine: https://dotnetfiddle.net/nNy8ar

CodePudding user response:

This should be possible with Linq:

uDict.FirstOrDefault(item => item.Key == "individualID").Value

You do need to be careful of your casing for your strings though if the item in the dictionary is individualID and you ask for individualId those are different keys. As in this example:

    public static void Main()
    {
        var dict = new Dictionary<string,string>();
        
        dict.Add("key", "Value");
        
        
        Console.WriteLine(dict.FirstOrDefault(x => x.Key == "KEY").Value);
        Console.WriteLine(dict.FirstOrDefault(x => x.Key == "kEY").Value);
        Console.WriteLine(dict.FirstOrDefault(x => x.Key == "KeY").Value);
        Console.WriteLine(dict.FirstOrDefault(x => x.Key == "KEy").Value);
        Console.WriteLine(dict.FirstOrDefault(x => x.Key == "Key").Value);
        Console.WriteLine(dict.FirstOrDefault(x => x.Key == "key").Value); //<-- this is the only processed line
    }
  • Related