c# - 如何判断 LINQ 扩展方法是否遭受双重枚举?

标签 c# .net linq

我想知道有什么规则可以判断 LINQ 代码的一部分是否遭受双重枚举?

例如,以下代码可能是双重枚举的迹象是什么?还有哪些其他迹象需要注意?

public static bool MyIsIncreasingMonotonicallyBy<T, TResult>(this IEnumerable<T> list, Func<T, TResult> selector)
    where TResult : IComparable<TResult>
{
    return list.Zip(list.Skip(1), (a, b) => selector(a).CompareTo(selector(b)) <= 0).All(b     => b);
}

最佳答案

传入其中一个:

public class OneTimeEnumerable<T> : IEnumerable<T>
{
  public OneTimeEnumerable(IEnumerable<T> source)
  {
    _source = source; 
  }

  private IEnumerable<T> _source;
  private bool _wasEnumerated = false;

  public IEnumerator<T> GetEnumerator()
  {
    if (_wasEnumerated)
    {
      throw new Exception("double enumeration occurred");
    }
    _wasEnumerated = true;
    return _source.GetEnumerator();
  }

}

关于c# - 如何判断 LINQ 扩展方法是否遭受双重枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14885875/

相关文章:

c# - 正则表达式没有从字符串中获取每个匹配项

c# - 何时需要dispose()的规则是什么?

sql - Include() 在 LINQ 中做什么?

c# - 您如何满足 WebApi 查询字符串中的 AND 和 OR 搜索?

c# - linq to entities 无法识别方法 int32 toint32

c# - C#查询txt文件中的特定行

c# - XSD.exe - 如何初始化从 xs :choice 创建的类型

c# - 为什么类 "Program"声明为静态的?

c# - 使用 C# 将 sql 查询的值分配给 CRM 中的字段

c# - 访问 5 字节结构比 8 字节慢得多