【发布时间】:2013-05-18 06:14:34
【问题描述】:
我正在尝试识别对象中的可枚举属性,然后将其转换为 Dictionary 对象
我用 lambda 表达式编写了一个 linq 查询来将列表转换为列表,我正在遵循这个 msdn article 中的示例
当我尝试在 LINQPad 中执行以下程序时,出现编译时错误
void Main()
{
var list = new List<int>();
list.Add(1);
list.Add(2);
var list2 = new List<string>();
list2.Add("ab");
list2.Add("xy");
var obj = new { x = "hi", y = list, z = list2 , a =1};
var properties = (obj.GetType()).GetProperties()
.Select(x => new {name =x.Name , value= x.GetValue(obj, null)})
.Where( x=> x.value != null && (x.value is IEnumerable) && x.value.GetType() != typeof(string) )
.Select(x => new {name = x.name, value= x.value});
Console.WriteLine(properties);
foreach( var item in properties)
{
var col = (IEnumerable) item.value;
foreach ( var a in col)
{
Console.WriteLine("{0}-{1}",item.name,a);
}
}
//compile time error in following line
var abc = properties.SelectMany(prop => (IEnumerable )prop.value, (prop,propvalue) => new {prop,propvalue} )
.Select( propNameValue =>
new {
name = propNameValue.prop.name,
value = propNameValue.propvalue
}
);
Console.WriteLine(abc);
}
方法的类型参数 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>, System.Func)' 不能从 用法。尝试明确指定类型参数。
如何重构 SelectMany 语句以消除错误,从而获得类似于嵌套 foreach 循环的输出?
【问题讨论】:
标签: c# reflection ienumerable linq