I’m trying to get a Value in a List<string> that’s in a Dictionary. I’ve tried dictionnaire[0][0] or dictionnaire[dictionnaires.ElementAt(index).Key].Value[0] but they don’t work. Any advice ?
What doesn’t work? Are getting an exception?
Without more info my guess is youre getting a null if you haven’t initialized the list at dict[0].
var dict = new Dictionary<int, List<string>>(); dict[0] = new List<string> {"hello"}; System.Console.WriteLine(dict[0][0])
Should print ‘hello’
You have several options, and dictionary[0][0]
should work as long as you have your dictionary initialized. Here is a top-level statement sample that should work for you.
I have an error that says “System.Collections.Generic.KeyNotFoundException : ‘The given key ‘0’ was not present in the dictionary.’ ”
Fixed formatting.
Hello, khalidabuhakmeh: code blocks using triple backticks (“`) don’t work on all versions of Reddit!
Some users see this / this instead.
To fix this, indent every line with 4 spaces instead.
FAQ
You can opt out by replying with backtickopt6 to this comment.
Always make life simpler for yourself.
It’s possible you’ve made an error in creating the list, assigning it the expected value, or in adding it to the dictionary.
Stepping through code which is clearly refactored out like it is above will help you figure out which step is failing, to see where the error is.
C# devs
null reference exceptions