我從MSDN sample以下代碼:Enumerable如何轉換爲字典?
if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
...
哪我重構如下:
Dictionary<uint, Row> rowDic = sheetData.Elements<Row>().ToDictionary(r => r.RowIndex.Value);
if (rowDic[rowIndex].Count() != 0)
{
row = rowDic[rowIndex];
...
現在,我感測到的是,如果Enumerable.ToDictionary <>方法實際上具有枚舉通過所有的數據,那麼這將是多餘的,但MSDN文檔沒有說明這個轉換是如何發生的。
我想使用的另一種方法是:
var foundRow = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex);
if (foundRow.Count() != 0)
{
row = foundRow.First();
...
不過,我想可能從以往的經驗,這將是更快,爲什麼就知道了。
謝謝。
*什麼*是多餘的?真的不清楚你在問什麼。但'ToDictionary' *不會*熱切地在整個輸入序列中迭代。 – 2013-05-08 13:48:19
如果你想知道哪兩件事情更快,那麼**運行它們**,你很快就會知道。 – 2013-05-08 15:01:48