【问题标题】:How to extract the data from dictionary Values in c#如何从C#中的字典值中提取数据
【发布时间】:2021-06-10 09:57:53
【问题描述】:

我有一个代码,我在 Dictionary Value 中获取 ViewModel。如何提取单个值。

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

            //}

        }

需要从 KVP.values 中提取值。

【问题讨论】:

  • 键值对(当前是对象)的值是否总是相同的类型?那么“var value”是否总是包含相同的属性?

标签: c# dictionary


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      using System.Linq;
      
      var query = from obj in dictionary.Values
                  select obj as SpecificType;
      
      foreach (var item in query)
      {
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-23
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多