Implement Dynamic orderby and linqorderby by using linq

Source: Internet
Author: User

Implement Dynamic orderby and linqorderby by using linq

Class Pet {public string Name {get; set;} public int Age {get; set ;}} void Main () {Pet [] pets = {new Pet {Name = "Tim", Age = 18}, new Pet {Name = "Allen", Age = 22 }, new Pet {Name = "Bill", Age = 20}; // if we want to sort by Age, it is easy to think of writing like this: var query = from p in pets orderby p. age select p; query. toList (). forEach (q => Console. writeLine (q. name + "" + q. age);/* get the result: tim 18 Bill 20 Allen 22 */} // But sometimes there are multiple sorting conditions in the project. If you want to sort by Name, sometimes you need to sort by Age. dynamic sorting: void Main () {Pet [] pets = {new Pet {Name = "Tim", Age = 18}, new Pet {Name = "Allen", Age = 22 }, new Pet {Name = "Bill", Age = 20}; Console. writeLine ("Before Orderby:/r/n"); pets. toList (). forEach (p => Console. writeLine (p. name + "" + p. age); var query = from p in pets orderby GetPropertyValue (p, "Age") select p; Console. writeLine ("/r/nAfter Orderby:/r/n"); query. toList (). forEach (q => Console. writeLine (q. name + "" + q. age);/* Before Orderby: Tim 18 Allen 22 Bill 20 After Orderby: tim 18 Bill 20 Allen 22 */}/* He asked hovertree.com */private static object GetPropertyValue (object obj, string property) {System. reflection. propertyInfo propertyInfo = obj. getType (). getProperty (property); return propertyInfo. getValue (obj, null );}

Recommended: http://www.cnblogs.com/roucheng/p/dushubiji.html

Related Article

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.