LINQ syntax structure
(from LINQ in Action)
For example, realize:
Queries a string that starts with a and is output in descending order.
C # code:
string[] list = { "adobe", "excel", "acer", "query", "async", "xianfen", "apple", "amazon", "player", "best", "wow" };
var result = from word in list
where word.StartsWith("a")
orderby word descending
select word;
result.ToList().ForEach(str => Console.WriteLine(str));
Output:
// async
// apple
// amazon
// adobe
// acer
The equivalence object-oriented syntax is:
var result = list.Where(str => str.StartsWith("a"))
.OrderByDescending(str => { return str; });
Where and orderbydescending are both ienumerable<t> extension methods, because the array type implements the interface, so you can call these extension methods directly.
The implementation of these extension methods is implemented in the enumerable type, so it is more straightforward to invoke the static method method of the enumerable type:
var result =
Enumerable.OrderByDescending(
Enumerable.Where(
list, str => str.StartsWith("a")), str => { return str; }
);
It can be seen from these reverse evolution that query syntax is a kind of "grammatical sugar". As mentioned earlier, the compile-time version is still 2.0, from which you can see some clues. If you want to further understand this implementation, you can use ildasm to view the IL source code and the Reflection class library source code.
The result type is ienumerable<telement> or a type derived from the Ienumerable<telement> interface.