Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Name Price
A ABC
B CBA
C 20
D 22
F 12
G 32
H 12

datatable will get thease value but i want to get the sum of Price column.when ever string value will be in row, It would be consider as a 0, Please provide solution for this.


Thanks,
Amod Kumar
Posted

The following LINQ statement sums the values that can be converted into an int:

C#
DataTable dt = ...
...
string col = "Price";
int sum = dt.AsEnumerable()
            .Aggregate(0,(n, r)=>
               {
                   int v;
                   return int.TryParse((r[col] as string) ?? string.Empty, out v)
                          ? n + v 
                          : n;
               }
             );

Or a bit easier to read:
C#
DataTable dt = ...
...
int sum = dt.AsEnumerable().Aggregate(0,(n,r)=>PriceField(r)+n);
...
static int PriceField(DataRow r)
{
    int v;
    return int.TryParse((r["Price"] as string) ?? string.Empty, out v) ? v : 0;
}

Or a further alternative:
C#
DataTable dt = ...
...
int sum = dt.AsEnumerable().Aggregate(0,SumPriceField);
...
static int SumPriceField(int n, DataRow r)
{
    int v;
    return int.TryParse((r["Price"] as string) ?? string.Empty, out v) ? n + v : n;
}


Cheers
Andi
 
Share this answer
 
v4
Comments
Frederico Barbosa 30-Oct-12 8:23am    
The price may have decimal points, albeit not shown in the example... so using double.TryParse() would be better.
Andreas Gieriet 30-Oct-12 9:13am    
Hello Frederico,
this is a valid point, thanks for mentioning this. Maybe "decimal" would be even better - depends on the application.
In any case, I assume the OP can adjust the code accordingly.
Cheers
Andi
SQL
double SgAmount = (from DataRow row in dt.Rows
                            where Double.TryParse(row.Field<string>("Test"), out total_SG) == true
                            select total_SG).Sum();
 
Share this answer
 
The following is the complete working and tested sample code.


C#
public static void main()
{
DataTable dt = new DataTable();
            dt.Columns.Add("Price");
            var dr = dt.NewRow();
            dr["Price"] = "12";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Price"] = "A1";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Price"] = "1";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Price"] = "2";
            dt.Rows.Add(dr);

            var sum = (from datarow in dt.AsEnumerable()
                       where (Program.NullableTryParseInt32(datarow["Price"].ToString()) != null)
                       select datarow["Price"]).ToArray().Sum(x => Convert.ToInt32(x));
} 


C#
public static int? NullableTryParseInt32(string text)
       {
           int value;
           return int.TryParse(text, out value) ? (int?)value : null;
       }



let me know whether this solved your problem.
 
Share this answer
 
v4
Comments
Amod72 29-Oct-12 6:38am    
Getting error.
The type arguments for method 'System.Data.DataRowExtensions.Field<t>(System.Data.DataRow, int)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Street Racers 29-Oct-12 8:25am    
updated the solution. Please check and revert back if any problem.
Andreas Gieriet 29-Oct-12 18:23pm    
Your LINQ naming is very odd:
from datatable in ...
is giving the wrong impression. What you get is a DataRow, not a DataTable.
I.e. you should name it
from row in ...
or alike.

Cheers
Andi
Street Racers 30-Oct-12 0:29am    
good catch. thanks for the comment. now i have changed the code.
SQL
double SgAmount = (from DataRow row in dt.Rows
                            where Double.TryParse(row.Field<string>("Test"), out total_SG) == true
                            select total_SG).Sum();



Thanks a lot Rajkumar_N and andy
 
Share this answer
 
Comments
Andreas Gieriet 30-Oct-12 12:08pm    
Why post twice and why post a solution to your answer yourself?
Please remove at least one of these.
Andi

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