So I'll preface this with it's a little difficult without the actual context of the code, and that all suggestions need to be checked to ensure they don't break the existing flow of control.
A few options:
- Breaking out repetitive operations into reusable methods
- Wrapper methods (within reason) to apply some common operations and call some other method
With the assumption that these are inside of a loop, and you're not relying on an exception from the Convert.ToDouble() call to break out then you might consider some approaches like follows.
Simplified from provided example. Assuming additional trailing '}' is not significant.
if (currentElement != null
&& !RowHasEmptyCells(firstGridRow, "Low", "High", "Mean", "StdDev")
&& newRow.Lenth != 0)
AddColourListWithSourceValue(firstGridRow, newRow, "Low", currentElement, opid, listCollectionLow);
AddColourListWithSourceValue(firstGridRow, newRow, "High", currentElement, opid, listCollectionHigh);
AddColourListWithSourceValue(firstGridRow, newRow, "Mean", currentElement, opid, listCollectionMean);
AddColourListWithSourceValue(firstGridRow, newRow, "StdDev", currentElement, opid, listCollectionStdDev);
Functions attempting to contain some of the previously duplicated logic:
//return true if any of the named cells in the row are 'empty'
bool RowHasEmptyCells(RowType row, params string cellNames)
return cellNames.Any(cellName => row[cellName].ToString() == string.Empty);
//RowType is the type of your row object (DataGridRow?)
void AddColourListWithSourceValue(RowType sourceRow, RowType newRow, string cellName, object currentElement, object opid, object listCollection)
double currentValue = Convert.ToDouble(sourceRow[cellName]);
AddColourList(currentElement, opid, currentValue, cellName, newRow, listCollection);
For the above double.Parse or .TryParse might be the way to go for a string > double conversion. If using Parse you could remove the empty cells check and just catch a FormatException/ArgumentNullException
This can likely be improved upon, but I've tried to make the flow of the main part a bit easier to follow whilst keeping roughly the same logic.
Edit 1: Sorry - fixed typo. Also AddColourListWithSourceValue() is just a guess at what's going on :)
Edit 2: Quick edit with @svick's correction on logic and suggestion for LINQ to check for empty. Inverted to allow for the positive method prefix 'Has' instead of a 'CellsNotEmpty'. Would welcome thoughts on !IsSomething() vs IsNotSomething()...
RowHasEmptyCells() as pointed out by @svick