One way to approach this is to define extension methods:
public static class DataTableExtensions
{
public static int SumColumnIntByIndex(this DataTable table, int id)
{
return table.AsEnumerable().Sum(x => x.Field<int>(id));
}
public static decimal SumColumnDecByIndex(this DataTable table, int id)
{
return table.AsEnumerable().Sum(x => x.Field<decimal>(id));
}
public static int SumColumnIntByID(this DataTable table, string id)
{
return table.AsEnumerable().Sum(x => x.Field<int>(id));
}
public static decimal SumColumnDecByID(this DataTable table, string id)
{
return table.AsEnumerable().Sum(x => x.Field<decimal>(id));
}
}
Sample use: assuming you have a valid DataTable, "dt," with a Decimal Field at Column Index #3, and Column #3 is named "Salary:"
decimal total1 = dt.SumColumnDecByIndex(3);
decimal total2 = dt.SumColumnDecByID("Salary");
You can easily add similar extensions for other Types (long, double, etc.). However note that as of .NET 5.0 IEnumerable.Sum can be used with only these Types:
double,double?
int,int?
decimal,decimal?
long,long?
float,float?
While you could do some re-factoring and make an extension that handles multiple Types, I personally believe that in writing Extensions the "DRY" principle ("don't repeat yourself") should be ignored, and that it's better to write separate Extensions ... which also gets you out of the problem of how to
return the right Type you'll have with a generic Extension.