user2548227
user2548227

Reputation: 29

Summing a Column of a Datatable

I am trying to sum the column "salary." Below is my table.

public static void dataTable()
{
DataTable table = GetTable();
}
static DataTable table;
public static DataTable GetTable()
{
table = new DataTable();
table.Columns.Add("player", typeof(string));
table.Columns.Add("age", typeof(double));
table.Columns.Add("position", typeof(stats.pos));
table.Columns.Add("ovalue", typeof(double));
table.Columns.Add("dvalue", typeof(double));
table.Columns.Add("team", typeof(stats.team));
table.Columns.Add("salary", typeof(int));
table.Columns.Add("contractYears", typeof(int));
table.Columns.Add("active", typeof(bool));

table.Rows.Add("AG", 24, stats.pos.SP, 0, 4.2, stats.team.S, 1, 5, true);
table.Rows.Add("AR", 30, stats.pos.SP, 0, 2.6, stats.team.S, 7, 2, true);
table.Rows.Add("JK", 22, stats.pos.SP, 0, 3.2, stats.team.S, 1, 6, true);
}
public class stats
{
public enum pos { fiB, seB, SS, thB, OF, C, DH, SP, RP };
public enum team { S };
}

Here is my attempt at adding the salary column:

try
{
    object sumobject = (object)table.Compute("Sum(salary)", "active=true");
    double sumdouble = Convert.ToDouble(sumobject);
    payrollLabel.Text = Convert.ToString(sumdouble);
}
catch
{ 
    MessageBox.Show("Error in payroll");
}          

However, the code always skips to the catch. It says that there is a null value in my column, but I didn't enter any. Any help would be greatly appreciated.

Upvotes: 0

Views: 431

Answers (3)

Siva
Siva

Reputation: 386

I am pretty sure it is something to do with the stats.pos or stats.team values. I removed the references and it works just fine. What do you have in stats object?

Wait... Are you initializing table before accessing it?

Upvotes: 1

Khan
Khan

Reputation: 18142

You could simplify it using LINQ:

Field as int:

var salarySum = table.AsEnumerable().Sum(x => x.Field<int>("salary"));    

As double:

var salarySum = table.AsEnumerable().Sum(x => x.Field<double>("salary"));

Upvotes: 2

Ehsan
Ehsan

Reputation: 32661

you can do this

yourtable.AsEnumerable().Sum(datarow => datarow.Field<int>("salary"));

Upvotes: 1

Related Questions