使用LINQ,是否可以从Select语句输出动态对象?如果有,怎么做呢?
本文关键字:如果 对象 动态 输出 是否 LINQ 语句 Select 使用 | 更新日期: 2023-09-27 18:05:04
目前在LINQ中,以下编译和工作很好:
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; };
}
然而,过去几个版本的。net/c#已经扩展了动态对象的作用,如ExpandoObject
,我想知道是否有一种方法基本上做到这一点:
var listOfFoo = myData.Select(x => new ExpandoObject{
someProperty = x.prop1,
someOtherProperty = x.prop2
});
显然,我已经尝试了上面的代码没有成功,但似乎我错过了一些东西
您应该能够创建一个新的匿名对象,而无需声明任何类型:
var listOfFoo = myData.Select(x => new {
someProperty = x.prop1,
someOtherProperty = x.prop2
});
没有什么可以阻止您使用Select
返回ExpandoObject的集合,您只是没有正确构造ExpandoObject
。有一种方法:
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);
}
}