Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I have a question about how to get values from my
Dictionary<string, List<object>>
, I tried all examples which I found in google, but still can't get something readable value.....
so, here is the code:
List<object> listValues = new List<object>();
listValues.Add(risk);
listValues.Add(validFrom);
listValues.Add(effectiveDate);
Dictionary<string, List<object>> dic = new Dictionary<string, List<object>>();
dic.Add(nameOfInsuredObject, listValues);
foreach (object value in dic.Values)
System.Console.WriteLine(value);
I can get key from dictionary, but with getting value I am stucked now....
And here is the result of this code:
Key => testInsObj
Values => System.Collections.Generic.List`1[System.Object]
So can anyone help me with it? I am new in C#, so maybe this is easy questions for others....
–
–
–
–
It seems you are looking for writing values of the list this way:
foreach (var value in dic.Values)
value.ForEach(Console.WriteLine);
In fact each element of the Dictionary is <string, List<Object>>
. So, when you want to write Value
part of the pair to console, you need a for loop to write each element of the List<object>
.
–
–
It is confusing for new C# users, how to access the dictionary.
When you do a foreach
on the dictionary, you get a KeyValuePair<TKey, TValue>
. Now this KeyValuePair<TKey, TValue>
, has 2 properties KeyValuePair.Key
and KeyValuePair.Value
, representing the Key
and Value
stored in the dictionary.
Also, the Value
in your case is a List<T>
, which means doing a Console.WriteLine
on it will not print the whole List<T>
(as some people expect), but just some reference string. You will have to "loop" over the list to print individual elements. Needless to say, depending on what you want to do with the element in the List<T>
, you can use LINQ
or some other common C# idiom.
foreach (var value in dic) {
Console.WriteLine(value.Key);
foreach (var item in value.Value)
Console.WriteLine(item);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.