How to calculate the sum of the datatable column in asp.net?

后端 未结 9 1132
悲哀的现实
悲哀的现实 2020-11-27 04:15

I have a DataTable which has 5 columns:

  • ID
  • Name
  • Account Number
  • Branch
  • Amount

The DataTable contains 5 rows.

相关标签:
9条回答
  • 2020-11-27 04:27
     this.LabelControl.Text = datatable.AsEnumerable()
        .Sum(x => x.Field<int>("Amount"))
        .ToString();
    

    If you want to filter the results:

     this.LabelControl.Text = datatable.AsEnumerable()
        .Where(y => y.Field<string>("SomeCol") != "foo")
        .Sum(x => x.Field<int>("MyColumn") )
        .ToString();
    
    0 讨论(0)
  • 2020-11-27 04:31

    You Can use Linq by Name Grouping

      var allEntries = from r in dt.AsEnumerable()
                                select r["Amount"];
    

    using name space using System.Linq;

    You can find the sample total,subtotal,grand total in datatable using c# at Myblog

    0 讨论(0)
  • 2020-11-27 04:31

    I think this solves

    using System.Linq;
    
    
    (datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))
    
    0 讨论(0)
  • 2020-11-27 04:35

    If you have a ADO.Net DataTable you could do

    int sum = 0;
    foreach(DataRow dr in dataTable.Rows)
    {
       sum += Convert.ToInt32(dr["Amount"]);
    }
    

    If you want to query the database table, you could use

    Select Sum(Amount) From DataTable
    
    0 讨论(0)
  • 2020-11-27 04:37

    Try this

    int sum = 0;
    foreach (DataRow dr in dt.Rows)
    {
         dynamic value = dr[index].ToString();
         if (!string.IsNullOrEmpty(value))
         { 
             sum += Convert.ToInt32(value);
         }
    }
    
    0 讨论(0)
  • 2020-11-27 04:40

    Compute Sum of Column in Datatable , Works 100%

    lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "").ToString();
    

    if you want to have any conditions, use it like this

       lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "srno=1 or srno in(1,2)").ToString();
    
    0 讨论(0)
提交回复
热议问题