Given a datatable that does not have a total column or row. How can I use LINQ to add a Total Column and Total row to create the table below?
TextColumn, NumberColumn0, NumberColumn1 Total
A 1 4 5
B 2 55 47
C 2.3 DBNULL 2.3
D 4 3 7
Total 9.3 62 61.3
Thanks!
Um, for those who need code. I'm using this currently for total column:
public static void CreateTotalColumnByType(DataTable table, Type valueType)
{
// create expression
string expression = string.Empty;
// do not count the first column (used for string field)
for (int columnIndex = 1; columnIndex < table.Columns.Count; ++columnIndex)
{
if (columnIndex != table.Columns.Count - 1)
{
// add +
expression += String.Format("[{0}] + ", table.Columns[columnIndex].ColumnName);
}
else
{
// last column so don't add plus
expression += String.Format("[{0}]", table.Columns[columnIndex].ColumnName);
}
}
// add total column
DataColumn totalColumn = new DataColumn("Total", valueType, expression);
table.Columns.Add(totalColumn);
}
but I'd like to replace it with LINQ.
There are a number of ways of doing this, depending on how you are getting this back you wouldn't even need to use LINQ.
You could do the following if you are using standard classes for data transport.
This way you have no need for LINQ. If you REALLY want to use LINQ you could use
If you have a variable number of columns or something similar, you might not have as much luck using LINQ, we would need to see more to get a true idea of what you are doing.
You could try like this one.
I just enhance p.cambell's solution a bit