【问题标题】:How is an Enumerable converted to a Dictionary?如何将 Enumerable 转换为 Dictionary?
【发布时间】: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


【解决方案1】:

更简洁的选择是:

var row = sheetData.Elements<Row>()
                   .FirstOrDefault(r => r.RowIndex == rowIndex);
if (row != null)
{
    // Use row
}

这只会遍历序列一次,一旦找到匹配项就会停止。

【讨论】:

  • 冗余 .Where 子句。 Lambda 可以移动到 .FirstOrDefault。例如.FirstOrDefault(r =&gt; r.RowIndex == rowIndex);
  • @spender:是的——我总是忘记这一点。 (计数同上)。不错的收获。
  • 相同。 Resharper 通常会救我。
【解决方案2】:

.Count()ToDictionary 方法都必须枚举所有元素才能获得结果。

这是最有效的实现:

var foundRow = sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);
if (foundRow != null)
{
    row = foundRow;

...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 2014-10-22
    相关资源
    最近更新 更多