On 02.03.13 01.01, Arne Vajhøj wrote:
[...]
I wouldn't bet that any other LINQ provider will behave the same.
Absolutely not.
http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx
says:
<quote>
Note: Deferred execution applies to all varieties of LINQ, including
LINQ to SQL, LINQ to Objects and LINQ to XML. However, of the three, it
is only LINQ to SQL that returns an expression tree by default. Or more
specifically, it returns an instance of the IQueryable interface that
references an expression tree. A query that returns IEnumerable still
supports deferred execution, but at least some larger portion of the
result is likely to have been generated than is the case with LINQ to
SQL. In other words, all types of LINQ support deferred execution, but
LINQ to SQL supports it more fully than LINQ to Objects or LINQ to XML.
Especially in case of IEnumerable<> I am in doubt.
It seem to do in the in my .NET version.
Tested with:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace E
{
public class Wrapper<T> : IEnumerable<T>
{
private List<T> real;
public Wrapper(List<T> real)
{
this.real = real;
}
IEnumerator IEnumerable.GetEnumerator()
{
Console.WriteLine("IEnumerable.GetEnumerator");
return real.GetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
Console.WriteLine("IEnumerable<T>.GetEnumerator");
return real.GetEnumerator();
}
}
public static class Fake
{
public static IEnumerable<TSource> FakeWhere<TSource>(this
IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
Console.WriteLine("IEnumerable<T>.Where");
return source.Where(predicate);
}
public static int FakeCount<TSource>(this IEnumerable<TSource>
source)
{
Console.WriteLine("IEnumerable<T>.Count");
return source.Count();
}
}
public class Program
{
public static void Main(string[] args)
{
List<int> lst = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine(lst.Where(v => v > 2 && v < 5).Count());
Wrapper<int> wrp = new Wrapper<int>(lst);
Console.WriteLine(wrp.FakeWhere(v => v > 2 && v <
5).FakeCount());
Console.ReadKey();
}
}
}
Arne