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);
}
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.
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.
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#? 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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With