2013-12-17 90 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