【问题标题】:LINQ unexpected behavior when returning IEnumerable and calling ToArray返回 IEnumerable 并调用 ToArray 时的 LINQ 意外行为
【发布时间】:2013-10-14 14:30:31
【问题描述】:

我注意到 LINQ 代码中有一些奇怪的行为,并使用两种方法将问题简化为以下最小示例:

IA Find(string n)
{
    IA result;
    if (!_dictionary.TryGetValue(n, out result))
    {
        throw Exception();
    }
    return result;
}

IEnumerable<IA> Find(IEnumerable<string> names)
{
    return names.Select(Find).ToArray();
}

这按预期工作。

现在,我删除了 .ToArray(),因此该方法如下所示:

IEnumerable<IA> Find(IEnumerable<string> names)
{
    return names.Select(Find);
}

此更改将导致不引发异常,即使某些名称在 _dictionary 中未找到,但存在于 names 参数中。

是什么导致了这种(对我而言)LINQ 的意外行为?

【问题讨论】:

  • 延迟执行。执行 Select 时不会迭代结果。

标签: c# .net arrays linq


【解决方案1】:

这是因为延迟执行。在您执行 Linq 之前,它不会被评估。

ToArray() 的调用会导致IEnumerable 的完整枚举,因此会发生异常。

第二种方法不枚举IEnumerable,并延迟执行,直到调用者需要它。


如果您要枚举 Find 的结果,例如

var result = Find(new[] { "name" }).ToList();

foreach (var found in Find(new[] { "name" }))
{
    ...
}

那么就会发生异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 2010-11-21
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    相关资源
    最近更新 更多