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
});
Question
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.
Solution
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
});
OTHER TIPS
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;
});
using (var command = this._context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "select * from persons";
command.CommandType = CommandType.Text;
this._context.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
var lst = new List<object>();
var lstColumns = new UserAccount().GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
while (result.Read())
{
var newObject = new object();
dynamic myobject = new ExpandoObject();
IDictionary<string, object> myUnderlyingObject = myobject;
for (var i = 0; i < result.FieldCount; i++)
{
var name = result.GetName(i);
var val = result.IsDBNull(i) ? null : result[i];
myUnderlyingObject.Add(name, val);
}
lst.Add(myUnderlyingObject);
}
return Ok(lst);
}
}