Tuesday, September 18, 2012

Compute Sum In Data table


We can compute in following methods:
1)   sumObject = dt.Compute("Sum(Salary)", "");          
2)   var sum = dt.AsEnumerable().Sum(x => x.Field<int>("Salary"));

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace sampleTest
{
    public partial class WebForm13 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("Salary",typeof(int));

            dt.Rows.Add(100);
            dt.Rows.Add(100);
            dt.Rows.Add(100);
            dt.Rows.Add(50);

            object sumObject;
         
            //First method
            sumObject = dt.Compute("Sum(Salary)", "");                
             
           
            //Second method
            var sum = dt.AsEnumerable().Sum(x => x.Field<int>("Salary"));

            var a = sumObject.ToString();
        }
    }
}

No comments:

Post a Comment