I have a series of DataRow objects, each with a bunch of different fields. What I want to do is create a new DataRow object with the total of certain decimal fields. Right now, my code looks something like this:
DataRow tally = myTable.NewRow();
foreach (DataRow row in myTable.Rows)
{
if (row["SomeField"] != DBNull.Value)
tally["SomeField"] = (tally["SomeField"] is DBNull ? 0 : (Decimal)tally["SomeField"]) + (Decimal)row["SomeField"];
// ...
}
I need to do the same with about 20 other fields, but I think the code is incredibly messy due to all the type-casting and null checking. Is there perhaps a way to refactor this code to be a bit more readable?
Note: I only want to tally up certain columns, otherwise I’d probably just loop through the columns in the DataRow rather than repeating the above code 20 times.
You could move your calculation code into a new method:
and use an array of indexes for the columns you want to tally: