In Linq, extension methods like Where
return an IEnumerable
collection, but sorting methods like OrderBy
return an IOrderedEnumerable
collection.
So, if you have a query that ends with OrderBy
(i.e. returns an IOrderedEnumerable
), you can't later append a Where
method - the compiler complains about the type being passed into Where
.
var query = Process.GetProcesses()
.Where(p => p.ProcessName.Length < 10)
.OrderBy(p => p.Id);
query = query.Where(p => p.ProcessName.Length < 5);
However, if you do it all in one query, it's fine!
var query = Process.GetProcesses()
.Where(p => p.ProcessName.Length < 10)
.OrderBy(p => p.Id)
.Where(p => p.ProcessName.Length < 5);
I've looked at the assembly in Reflector to see if the compiler was re-ordering any of the operations, but it doesn't seem to have. How does this work?