Ole*_*egI 0 .net c# 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;}
}
Run Code Online (Sandbox Code Playgroud)
而我需要创建Dictionary其中的键--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());
}
Run Code Online (Sandbox Code Playgroud)
你不能投,但你可以使用ToDictionary:
itemList.ToDictionary(s=>s.Name, s.Address);
Run Code Online (Sandbox Code Playgroud)