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

Matt Cashatt picture Matt Cashatt · Mar 21, 2013 · Viewed 29k times · Source

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.

Answer

CassOnMars picture CassOnMars · Mar 21, 2013

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