从List <t>属性中检索值并强制转换为Dictionary <string,string> C#

时间:2017-02-03 15:53:25

标签: c# .net linq dictionary casting

情况如下:

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

1 个答案:

答案 0 :(得分:7)

你不能施放它但你可以使用ToDictionary:

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