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