【问题标题】:Dynamically adding the columns in group by clause of linq动态添加linq的group by子句中的列
【发布时间】:2013-09-17 06:54:33
【问题描述】:

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

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

下面是代码sn-p:

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)),
                    };

【问题讨论】:

  • 您找到解决方案了吗?我有一个非常相似的问题要解决。

标签: linq datatable


【解决方案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 包。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-03-06
  • 2014-12-26
  • 2014-03-05
  • 2023-04-02
  • 2011-01-03
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
相关资源
最近更新 更多