我有一個DataGridView,實際上可能有多達2000行和100列。我想循環遍歷所有單元格,並根據單元格中基礎數據的性質將內容添加到列表中。該代碼目前看起來是這樣的:最快的單元格迭代方法
for (var columnIndex = 1; columnIndex < edgv.ColumnCount; columnIndex++)
{
for (var rowIndex = 1; rowIndex < edgv.RowCount; rowIndex++)
{
var currentValue = edgv[columnIndex, rowIndex].Value as ISomeInterface;
if (currentValue != null && (currentValue.GetType().Equals(typeof(SomeClass).FullName))
&& (((SomeClass)currentValue).Attribute != null))
{
values.Add(currentValue);
}
}
}
此代碼適用於較小的電網,但似乎陷入癱瘓(如果不是搪塞了完全)時,列數和行數開始越來越大。我想知道是否將for循環更改爲foreach循環可能會有所幫助,並且我願意接受其他想法。
有什麼想法?
一個foreach仍然是一個循環。不要猜測瓶頸,嘗試測試它。如果您註釋掉當前的代碼,它運行得有多快? – LarsTech
我想你應該旋轉一個原型並自己測試一下。這是很好的編程業力。 – Will
這似乎很奇怪'currentValue.GetType()。Equals(typeof(SomeClass).FullName)''。爲什麼不只是'currentValue。GetType()== typeof(SomeClass)''''''''或'currentValue是SomeClass',或者更好地使用'作爲SomeClass'來代替,你只需要'if(currentValue!= null && currentValue.Attribute!= null)' – juharr