繁体   English   中英

如何从 c# 中的字典值中提取数据

[英]How to extract the data from dictionary Values in c#

我有一个代码,我在 Dictionary Value.How 中获取 ViewModel 来提取各个值。

        foreach (KeyValuePair<string, object> kvp in dictionary)
        {
            var key = kvp.Key;
            var value = kvp.Value;
            //foreach (var vp in value)
            //{

            //}

        }

需要从 KVP.values 中提取值。

在此处输入图像描述

您可以使用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());
}

我会提到提出这个问题的人试图从属性中获取值,因此可以通过这种方式完成:

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();
                };  
            }
            
        }
    }
}

您在字典的值部分中有一个object类型。 您可以将object向下转换为您的SpecificType ,以便能够直接访问 object 属性。 所以:

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.

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