2017-02-03 43 views
0

这里的情况是:检索列表<T>财产和投值到词典<字符串,字符串> C#

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

,我需要创建词典,其中关键 - 酒吧类属性的名称和值 - 相关栏类值。在这里我也尝试:

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

,并且你你已经尝试什么有什么问题? – Servy

+0

@Servy无法将它转换成IEnumerable的字典 – OlegI

+0

您的字典应该是Dictionary > – jdweng

回答

7

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

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

这样你就可以更清楚地知道你收藏的PK是什么。 – CDove

相关问题