Take
var query = Process.GetProcesses()
.OrderBy(p => p.WorkingSet64)
.ThenByDescending(p => p.Threads.Count);
.Where(p => p.ProcessName.Length < 9);
It works fine. Take
var query = Process.GetProcesses()
.OrderBy(p => p.WorkingSet64)
.ThenByDescending(p => p.Threads.Count);
//.Where(p => p.ProcessName.Length < 9);
query = query.Where(p => p.ProcessName.Length < 9);
This does not work. I do not understand why the first method works. In my mind these queries are the same. ThenByDescending returns IOrderedEnumerable<T> which is piped into Where(). The first method should not work because Where only works with IEnumerable<T>. Alas…it does work.
How does this processing pipeline function?
The difference is because of a misunderstanding of the
varkeyword and LINQ queries.var (C# reference)
Using the
varkeyword is the same as specifying the same type as the right side of the assignment. It does not mean that you can assign any type to the variable.In LINQ queries, most of the basic expressions return an
IEnumerable, but it many cases, they do not return just anIEnumerable. Instead, they return an type that inherits fromIEnumerable.In this case, you are doing the equivalent of this:
and
The reason that the first snippet works is because
IOrderedEnumerableinherits fromIEnumerable, so you can use it as such.To fix the problem in the second example, you need to explicitly declare
queryasIEnumerable<Process>.