开发者

c# LINQ creating anonymous type from run-time information

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 value开发者_StackOverflow中文版s for eachcolumn average
                     };

As far as I can tell you cannot enumerate within an anonymous scope?

Is there a way to do this?

Thanks.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜