Using LINQ, is it possible to output a dynamic object from a Select statement? If so, how?

孤街浪徒 提交于 2020-01-02 00:53:07

问题


Presently in LINQ, the following compiles and works just fine:

var listOfFoo = myData.Select(x => new FooModel{
     someProperty = x.prop1,
     someOtherProperty = x.prop2
});

public class FooModel{
     public string someProperty  { get; set; };
     public string someOtherProperty  { get; set; };
}

However, the past few versions of .NET/C# have expanded the role of dynamic objects such as the ExpandoObject and I am wondering if there is a way to basically do this:

var listOfFoo = myData.Select(x => new ExpandoObject{
     someProperty = x.prop1,
     someOtherProperty = x.prop2
});

Obviously, I have already tried the code above without success, but it seems like I am missing something.


回答1:


You should be able to create a new anonymous object without any type declared:

var listOfFoo = myData.Select(x => new {
    someProperty = x.prop1,
    someOtherProperty = x.prop2
});



回答2:


There is nothing preventing you from using Select to return a collection of ExpandoObject's, you just aren't properly constructing the ExpandoObject. Here's one way:

var listOfFoo = myData.Select(x =>
    {
        dynamic expando = new ExpandoObject();
        expando.someProperty = x.prop1;
        expando.someOtherProperty = x.prop2;
        return (ExpandoObject)expando;
    });


来源:https://stackoverflow.com/questions/15554917/using-linq-is-it-possible-to-output-a-dynamic-object-from-a-select-statement-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!