【问题标题】:Retrieve values from List<T> property and cast to Dictionary<string,string> C#从 List<T> 属性中检索值并转换为 Dictionary<string,string> C#
【发布时间】:2017-02-03 15:53:24
【问题描述】:

情况如下:

public class Foo
{
  public string Name {get;set;}
  public List<Bar> barITems{get; set;}
}
public class Bar
{
  public string Name{get; set;}
  public string Address{get; set;}
}

我需要创建 Dictionary where key - Bar 类属性名称和值 - Bar 类相关值。这是我所做的尝试:

    Type a = typeof(Foo);
    PropertyInfo[] properties = a.GetProperties();           
    foreach (var property in properties)
    {                       
        if(property.Name == "barItems")
        {
          var barProperty = property.GetValue(Foo);
          var itemList= barProperty as IEnumerable;
          var barDictionary = new Dictionary<string,string>();
          barDictionary = itemList;  //how to cast it ?           
          continue;
        }
        fooDictionary.Add(property.Name, property.GetValue(Foo).ToString());
    }

【问题讨论】:

  • 您尝试过的方法有什么问题?
  • @Servy 无法从 IEnumerable 将其转换为字典
  • 你的字典应该是 Dictionary>
  • 这是有道理的。 itemList 的类型为 IEnumerable,您尝试将其分配给不接受 List 的 Dictionary。当您可以滚动列表并以这种方式为字典分配键值对时,为什么还要使用反射?
  • 我试图测试你的代码,但它在这一行有一个错误: var barProperty = property.GetValue(Foo); Foo 是一种类型,但您用作变量。

标签: c# .net linq dictionary casting


【解决方案1】:

你不能转换它,但你可以使用 ToDictionary:

itemList.ToDictionary(s=>s.Name, s.Address);

【讨论】:

  • 这样你也更清楚你收藏的PK是什么。
猜你喜欢
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多