简体   繁体   English

C#从字典获取值 <string, List<object> &gt;

[英]C# getting values from Dictionary<string, List<object>>

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..... 我有一个关于如何从我的Dictionary<string, List<object>>获取值的问题,我尝试了所有在google中找到的示例,但仍然无法获得可读的值.....

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.... 我是C#的新手,所以对其他人来说这也许是个简单的问题。

It is confusing for new C# users, how to access the dictionary. 对于新的C#用户来说,如何访问字典令人困惑。

When you do a foreach on the dictionary, you get a KeyValuePair<TKey, TValue> . 在字典上执行foreach时,会得到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. 现在,此KeyValuePair<TKey, TValue>具有2个属性KeyValuePair.KeyKeyValuePair.Value ,表示存储在字典中的KeyValue

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. 同样,您所用的ValueList<T> ,这意味着在其上执行Console.WriteLine不会打印整个List<T> (正如某些人所期望的那样),而只会打印一些参考字符串。 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. 不用说,根据要对List<T>的元素执行的操作,可以使用LINQ或其他一些常见的C#习惯用法。

foreach (var value in dic) {
    Console.WriteLine(value.Key);
    foreach (var item in value.Value)
        Console.WriteLine(item);
}

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>> . 实际上,字典的每个元素都是<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> . 因此,当您要将对中的Value部分写入控制台时,需要一个for循环来写入List<object>每个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM