簡體   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