LINQ Learning (3) grammatical structure

Source: Internet
Author: User
Tags acer

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.