我會做你的代碼的主要變化是
- 刪除
return
聲明,因爲這將退出我們的方法過早
- 使用
List<double>
來存儲你的雙打(你沒有申報這是很好的,因爲我們不知道字符串中有多少項會成功轉換爲雙精度)
- 在將它添加到
List
時使用val
變量,因爲double.TryParse
已分配了價值這個VAR已經可以。
我還添加了檢查,以確保變量numRows
不大於字符串數組大,因爲這會在我們的循環會導致異常:
// Mock values read from file
var input = new StringBuilder();
input.Append("0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,");
input.Append("1.1389,0.50494,0.24976,0.6598,0.1666,0.24976,497.42,0.73378,");
input.Append("2.6349,0.24976,0.14942,43.37,1.2479,0.21402,0.11998,0.47706,");
input.Append("0.50494,0.60411,1.4582,1.7615,5.9443,0.11788,593.27,0.50591,");
input.Append("0.12804,0.66295,0.14942,94.14,3.8772,0.56393,0.21402,1.741,");
input.Append("1.5225,49.394,0.1853,0.11085,2.042,0.051402,0.12804,114.42,");
input.Append("71.05,1.0097,348690,0.12196,0.39718,0.87804,0.37854,0.25792,");
input.Append("2.2437,2.248,0.001924,8.416,5.1372,82.658,4.4158,7.4277");
string[] values_in_string = inputString.ToString().Split(',');
// Declare values_in_double as a List so we don't have to worry about sizing
List<double> values_in_double = new List<double>();
// We will get errors if numCols is larger than our string array, so to be safe,
// set a variable that is the smallest of either numCols or our string array length
var numIterations = Math.Min(numCols, values_in_string.Length);
for (int x = 0; x < numIterations; x++)
{
double val;
// If TryParse succeeds, 'val' will contain the double value, so add it to our List
if (double.TryParse(values_in_string[x], NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out val))
{
values_in_double.Add(val);
}
}
還有在更短的方式編寫這段代碼。該生產線基本上是說:對於values_in_string
每個項目,凡double.TryParse
回報true
,選擇val
(項目作爲一個值)和所有val
項目轉換成List
:
string[] values_in_string = inputString.ToString().Split(',');
double val = 0;
List<double> values_in_double = values_in_string
.Where(value => double.TryParse(value, NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out val))
.Select(v => val)
.ToList();
你爲什麼'return'如果一個值不轉換?爲什麼不只是「繼續」? 'return'會退出你所在的任何方法,'continue'只會跳過這個項目並繼續下一個。至少,你可能需要調用'break',它會跳出'for'循環並繼續使用它之後的任何代碼。或者檢查我的答案,以稍微不同的方式來做到這一點。 –
如果TryParse返回false,則返回false,因爲對於這種情況,如果某些值未轉換,我不感興趣,所以我不能丟失數據。 –