23

目前在 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
});

显然,我已经尝试过上面的代码但没有成功,但似乎我遗漏了一些东西。

4

3 回答 3

44

您应该能够在没有声明任何类型的情况下创建一个新的匿名对象:

var listOfFoo = myData.Select(x => new {
    someProperty = x.prop1,
    someOtherProperty = x.prop2
});
于 2013-03-21T18:07:05.837 回答
12

没有什么可以阻止您使用Select来返回 ExpandoObject 的集合,您只是没有正确构建ExpandoObject. 这是一种方法:

var listOfFoo = myData.Select(x =>
    {
        dynamic expando = new ExpandoObject();
        expando.someProperty = x.prop1;
        expando.someOtherProperty = x.prop2;
        return (ExpandoObject)expando;
    });
于 2013-03-21T18:16:21.253 回答
0
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);
            }
        }
于 2021-09-14T13:33:32.323 回答