C# LINQ 从运行时信息创建匿名类型
假设我有一个在运行时填充的列名称列表。我将如何使用 LINQ 表达式为每个列名称创建平均值,在按查询分组内,例如:
var result = from data in view.AsEnumerable()
group data by new {Group = data.Field<string>("group_no")}
into grp
select new
{
Group = grp.Key.Group,
//Add anonymous values for eachcolumn average
};
据我所知,您不能在匿名范围内枚举?
有办法做到这一点吗?
谢谢。
Say I have a List of columnNames that is populated at run-time. How would I use a LINQ expression to create average values for each of those columnNames, inside a grouped by query such as:
var result = from data in view.AsEnumerable()
group data by new {Group = data.Field<string>("group_no")}
into grp
select new
{
Group = grp.Key.Group,
//Add anonymous values for eachcolumn average
};
As far as I can tell you cannot enumerate within an anonymous scope?
Is there a way to do this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能。
相反,您可以制作一本字典:
需要
Convert.ToDouble
,因为我不知道可能是什么类型,而Average
需要特定的数字类型。如果所有列都是相同的数字类型,您可以将其替换为强制转换。
You can't.
Instead, you can make a dictionary:
The
Convert.ToDouble
is needed since I don't know what tyhpe the coulmn is, andAverage
needs a specific numeric type.If all of the columns are the same numeric type, you can replace that with a cast.
匿名类型是在编译时创建的。您无法根据运行时信息创建一个。此外,匿名类型具有方法范围,这意味着您无法返回它们并在其他地方使用它们。
根据您想要做什么(顺便问一下,您想要做什么?),您可能会考虑动态类型。从(例如)ExpandoObject 开始。或者,在运行时生成编译类型可能是有意义的。看看(例如)TypeBuilder。
Anonymous types are created at compile-time. You cannot create one from runtime information. Moreover, anonymous types have method scope, meaning that you couldn't return them and use them somewhere else.
Depending on what you're trying to do (what are you trying to do, by the way?), you might look at dynamic types. Start with (e.g.) ExpandoObject. Alternatively, generating a compiled type at runtime might make sense. Look at (e.g.) TypeBuilder.