[英]How to extract the data from dictionary Values in c#
I have a code where I am getting ViewModel inside Dictionary Value.How to extract the individual values.我有一个代码,我在 Dictionary Value.How 中获取 ViewModel 来提取各个值。
foreach (KeyValuePair<string, object> kvp in dictionary)
{
var key = kvp.Key;
var value = kvp.Value;
//foreach (var vp in value)
//{
//}
}
Need to extract the values from KVP.values.需要从 KVP.values 中提取值。
You can use GetProperties :您可以使用GetProperties :
PropertyInfo[] myPropertyInfo;
// Get the properties of 'Type' class object.
myPropertyInfo = value.GetType().GetProperties();
Console.WriteLine("Properties of System.Type are:");
for (int i = 0; i < myPropertyInfo.Length; i++)
{
Console.WriteLine(myPropertyInfo[i].ToString());
}
I would mention that the person who asked this question tried to get values from properties so it can be done in this way:我会提到提出这个问题的人试图从属性中获取值,因此可以通过这种方式完成:
using System;
using System.Collections.Generic;
using System.Linq;
namespace StoVerF1
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, Car> dictionarySet = new Dictionary<string, Car>();
dictionarySet.Add("Audi", new Car { maxSpeed = 220 });
dictionarySet.Add("BMW", new Car { maxSpeed = 235 });
dictionarySet.Add("Ferrari", new Car { maxSpeed = 285 });
var dataFromReflectionKeys = (dictionarySet.Keys as IEnumerable<string>)?.ToList();
foreach (string keyDic in dataFromReflectionKeys)
{
Console.WriteLine($"For auto {keyDic} type info :");
var dictElem = (dictionarySet[keyDic] as Car);
if (dictElem != null)
{
var propeties = dictElem.GetType().GetProperties();
foreach (var prop in propeties)
{
Console.WriteLine($"Value of property{prop.Name} is {prop.GetValue(dictElem)}");
}
var fields = dictElem.GetType().GetFields();
var methods = dictElem.GetType().GetMethods();
};
}
}
}
}
You have an object
type in the value part of the dictionary.您在字典的值部分中有一个
object
类型。 You can downcast object
to your SpecificType
to be able to access the object properties directly.您可以将
object
向下转换为您的SpecificType
,以便能够直接访问 object 属性。 Therefore:所以:
using System.Linq;
var query = from obj in dictionary.Values
select obj as SpecificType;
foreach (var item in query)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.