C# 使用 LINQ,是否可以从 Select 语句中输出动态对象?如果是这样,如何?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15554917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using LINQ, is it possible to output a dynamic object from a Select statement? If so, how?
提问by Matt Cashatt
Presently in LINQ, the following compiles and works just fine:
目前在 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; };
}
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:
但是,过去几个版本的 .NET/C# 已经扩展了动态对象的作用,例如ExpandoObject
,我想知道是否有一种方法可以基本上做到这一点:
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.
显然,我已经尝试了上面的代码但没有成功,但似乎我错过了一些东西。
采纳答案by doctorless
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
});
回答by Servy
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:
没有什么可以阻止您使用Select
返回 ExpandoObject 的集合,只是您没有正确构造ExpandoObject
. 这是一种方法:
var listOfFoo = myData.Select(x =>
{
dynamic expando = new ExpandoObject();
expando.someProperty = x.prop1;
expando.someOtherProperty = x.prop2;
return (ExpandoObject)expando;
});