Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one tell if a LINQ extension method is suffering from double enumeration?

Tags:

c#

.net

linq

I am wondering what rules there are to tell if a portion of LINQ code is suffering from double enumeration?

For example, what are the telltale signs that the following code might be double enumerating? What are some other signs to look out for?

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);
}
like image 530
Contango Avatar asked Feb 14 '13 23:02

Contango


People also ask

How many times can you re-evaluate a LINQ expression?

Due to LINQ expressions being deferred in execution, it is a general rule of thumb not to re-evaluate the expression more than once. For LINQ extension methods, this is even more important not to re-iterate. You have to be diligent, as it is very to unintentionally do the wrong thing.

Are LINQ extension methods easy to write?

LINQ extension methods are often easy to describe, and quickly you can build something that seems to work. But there are pitfalls that you must be aware of in order for your code to work in the general case. This article describes the best practices you need to follow when writing LINQ extension methods.

How are LINQ query operators implemented in Java?

The LINQ’s standard query operators such as select, where, etc. are implemented in Enumerable class. These methods are implemented as extension methods of the type IEnumerable<T> interface.

How to implement extension methods in C #?

How to implement extension methods in C#? Understanding the LINQ Extension Method. The LINQ’s standard query operators such as select, where, etc. are implemented in Enumerable class. These methods are implemented as extension methods of the type IEnumerable<T> interface.


Video Answer


1 Answers

Pass in one of these:

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();
  }

}
like image 91
Amy B Avatar answered Sep 17 '22 13:09

Amy B