【问题标题】:Complie Time Error: SelectMany编译时错误:SelectMany
【发布时间】: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


    【解决方案1】:

    我想简化您的问题,假设您有两个列表:listIntlistString

    var listInt = new List<int> { 1, 2 };
    var listString = new List<string> { "ab", "xy" };
    

    然后创建一个listObject,如下所示:

    var listObject = new object[] { listInt, listString };
    

    如果你这样做SelectMany:

    var output = listObject.SelectMany(list => list);
    

    由于两个列表包含不同的类型,因此您将得到相同的错误。你会想投到IEnumerable&lt;object&gt; 喜欢:

    var output = listObject.SelectMany(list => (IEnumerable<object>)list);
    

    但它不适用于listInt,因为协变体不支持值类型。只是我认为的唯一解决方案:

    var output = listObject.SelectMany(list => ((IEnumerable)list).Cast<object>());
    

    所以,为了解决你的问题,你可以改变:

    prop => ((IEnumerable)prop.value).Cast<object>();
    

    【讨论】:

    • @Coung Le 感谢您的解释,让我更容易理解。
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2010-09-30
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    相关资源
    最近更新 更多