【问题标题】:How to perform Sum of a column dynamically in C#?如何在 C# 中动态执行列的总和?
【发布时间】:2013-08-07 17:03:54
【问题描述】:

我正在使用 System.Linq.Dynamic 对使用 linq 的列进行动态分组,需要执行

我如何对列进行求和,即(总和(存款))。用户将在运行时选择表和列。 例如:上表有 Territory、State、BankName、Year、QuarterFromMainT

假设用户已选择这些列进行分组(Territory、State、BankName)并且现在想要对列 ex:Deposits 求和。我怎样才能做到这一点?因为只有 ASEnumerable 和 AsQueryable 只有 sum。我们需要执行groupby和sum

点击here进一步说明,我的代码是:

这里 t1 是表,qfields 是一个包含分组列的列表。

如何在 groupby 之后使用 linq 对列求和?

【问题讨论】:

标签: c# linq


【解决方案1】:

你是这个意思吗?如果没有,请忽略...

var query = rows
    .GroupBy(row => new { row.Territory, row.State, row.BankName })
    .Select(group => new
    {
        group.Key.Territory, group.Key.State, group.Key.BankName,
        Deposits = group.Sum(row => row.Deposits)
    });

【讨论】:

  • 我怎么算?
  • 查询具有非静态的动态列,即用户将在运行时选择要分组的表和列以及要求和的列。我该怎么做?
【解决方案2】:

您需要设置页脚文本以显示您的总金额

例子:

 <asp:BoundField DataField="Deposits" 
             FooterText="Total Desposits" />

在 Gridview 中你需要像这样编写代码

 Gridview.Columns[4].FooterText = dt.AsEnumerable().Select(x => x.Field<int>("Desposits")).Sum().ToString();

        Gridview.DataSource = dt;

        Gridview.DataBind();

它在我的应用程序中工作。您可以根据自己的方便使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2020-08-09
    • 2018-01-04
    • 1970-01-01
    • 2021-03-20
    相关资源
    最近更新 更多