简体   繁体   中英

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.

        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.

在此处输入图像描述

You can use 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. You can downcast object to your SpecificType to be able to access the object properties directly. Therefore:

using System.Linq;

var query = from obj in dictionary.Values
            select obj as SpecificType;

foreach (var item in query)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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