Click here to Skip to main content
15,877,168 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Dear All


Could any one please tell me how to findout the sum of top 10 rows of a column in a datatable in asp .net.

I have a datatable employee

which has fileds
Id,PersonName, Amount


I would like to find the total Amount of top 10 rows. There are above 10000 rows in my datatable.I just want to findout the sum of first 10 rows

Please help me


Thank You...
Posted
Comments
phil.o 10-Jun-14 3:39am    
What have you tried?
DamithSL 10-Jun-14 4:09am    
what is the column type?

 
Share this answer
 
try this.. :)

C#
  DataTable dtGetadata=GetDataTable();

//call method GetDataTable();



C#
public DataTable GetDataTable ()
       {
            DataTable dtData=new DataTable();
           //Fill datatable with data

           int Total=0;

           for(int i=0;i<10;i++)
           {
               Total+=Convert.ToInt32(dtData.Rows[i]["amount"]);

           }
               dtData.Rows.Add("","Total",Total);

           return dtData;

       }
 
Share this answer
 
.net 3.5 + you can try below with LINQ, if your column type is int and the column name is Amount

C#
var sum = datatable.AsEnumerable().Take(10)
    .Sum(x => x.Field<int>("Amount" ));</int>
 
Share this answer
 
Hello ,
Enumerable.Take function returns a specfied number of sequence from starting position.For more details check this link .
Refer:Link
Now try this solution :
var Total = yourdatatable.AsEnumerable().Take(10)
    .Sum(x => x.Field<datatype>("Amount" ));
//here first convert the DataTable to IEnumerable<t> objects. As this object can be used for LINQ expression .Then make a Sum function to get the result . here datatype may be decimal or int. Give the datatype for corresponding "Amount" field .
</t></datatype>
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900