1

我从服务中获取数据表。我正在使用 linq 来计算总和新列。我想要数据表中的所有原始数据加上在 linq 中计算的新列。

问题是数据表中的列不固定。我将如何在 linq 的 select 子句中动态添加列。

下面是代码片段:

DataTable dt = ds.Tables[0];
var orderCtr =
from o in dt.AsEnumerable()
where o.Field<string>(Constants.GENDER_NAME) != "Unknown"
group o by new
{
                    odr_id = o.Field<int>(Constants.ORDER_ID),
                    //NEED TO ADD COLUMNS DYNAMICALLY HERE. MEANS IF THEY ARE IN DATATABLE.
                }
                    into g
                    select new
                    {
                         //NEED TO ADD COLUMNS DYNAMICALLY HERE. MEANS IF THEY ARE IN DATATABLE.
                        odr_id = g.Key.odr_id,
                        ac_gr_imp = g.Sum(r => r.Field<long>(Constants.GENDER_IMPRESSION)),
                        ac_gr_clk = g.Sum(r => r.Field<long>(Constants.GENDER_CLICK)),
                        Ctr = (double)g.Sum(r => r.Field<long>(Constants.GENDER_IMPRESSION)) / g.Sum(r => r.Field<long>(Constants.GENDER_CLICK)),
                    };
4

1 回答 1

-1

您可能对动态 LINQ 库感兴趣。动态 LINQ 允许您通过构建字符串来指定查询或部分查询。

Scott Guthrie 在 2008 年描述了它(http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx)如果您使用 .NET 4 ( http://www.nuget.org/packages/System.Linq.Dynamic ) ,还有一个 NuGet 包。

于 2013-09-17T07:01:16.507 回答