C# LINQ 从运行时信息创建匿名类型

发布于 2024-10-27 04:58:23 字数 517 浏览 1 评论 0原文

假设我有一个在运行时填充的列名称列表。我将如何使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半城柳色半声笛 2024-11-03 04:58:23

你不能。

相反,您可以制作一本字典:

Averages = table.Columns.Cast<DataColumn>().ToDictionary(
    c => c.ColumnName, 
    c => grp.Average(dr => Convert.ToDouble(dr[c]))
)

需要 Convert.ToDouble ,因为我不知道可能是什么类型,而 Average 需要特定的数字类型。
如果所有列都是相同的数字类型,您可以将其替换为强制转换。

You can't.

Instead, you can make a dictionary:

Averages = table.Columns.Cast<DataColumn>().ToDictionary(
    c => c.ColumnName, 
    c => grp.Average(dr => Convert.ToDouble(dr[c]))
)

The Convert.ToDouble is needed since I don't know what tyhpe the coulmn is, and Average needs a specific numeric type.
If all of the columns are the same numeric type, you can replace that with a cast.

初与友歌 2024-11-03 04:58:23

匿名类型是在编译时创建的。您无法根据运行时信息创建一个。此外,匿名类型具有方法范围,这意味着您无法返回它们并在其他地方使用它们。

根据您想要做什么(顺便问一下,您想要做什么?),您可能会考虑动态类型。从(例如)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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文