【发布时间】:2013-05-02 18:51:59
【问题描述】:
我有来自MSDN sample的以下代码:
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确实急切地遍历整个输入序列。 -
如果您想知道两件事中哪一个更快,然后运行它们,您很快就会发现。
标签: c# .net linq enumerable