2013-12-17 59 views
1

有没有其他方法可以优化下面的代码?我觉得下面的代码对于它所执行的操作来说是巨大的。针对相同条件的多个值

if ((currentElement == null || 
    (firstGridRow["Low"].ToString() == string.Empty || 
    firstGridRow["High"].ToString() == string.Empty || 
    firstGridRow["Mean"].ToString() == string.Empty || 
    firstGridRow["StdDev"].ToString() == string.Empty))) 
{ 
    continue; 
} 

if (newRow.Length != 0) 
{ 
    AddColorList(currentElement, opid, currentLow, "Low", newRow, listCollectionLow); 
    AddColorList(currentElement, opid, currentHigh, "High", newRow, listCollectionHigh); 
    AddColorList(currentElement, opid, currentMean, "Mean", newRow, listCollectionMean); 
    AddColorList(currentElement, opid, currentStdDev, "StdDev", newRow, listCollectionStdDev); 
} 
+3

你应该问这对http://codereview.stackexchange.com/! –

+1

什么是firstGridRow?以及循环如何看起来像? –

+0

为什么在每个循环迭代中检查'firstGridRow [“Low”]和其他列,即使它始终是同一行? –

回答

3

您可以使用LINQ,像这样:

private static readonly string[] AllKeys = new[] {"Low", "High", "Mean", "StdDev"}; 


if (currentElement == null || ALlKeys.Any(k => gridRow[k].ToString() == string.Empty)) { 
    ... 
} 
if (newRow.Length != 0) { 
    foreach (var key in AllKeys) { 
     AddColorList(currentElement, opid, currentLow, key, newRow, listCollectionLow); 
    } 
} 
+0

您可以在这里使用string.IsNullOrEmpty(gridRow [key]) – Tobiasz

+0

@Tobias正确。然而'string'永远不会是'null',所以我不确定这在这里有多大用处。 – dasblinkenlight

+0

它说'string'永远不'null'? – Tobiasz