CSharp3.0中扩展方法,直接看代码:
/// <summary> /// Orders the by. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list">The list.</param> /// <param name="sortExpression">The sort expression.</param> /// <returns>IEnumerable<T></returns> public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, string sortExpression) { sortExpression += ""; string[] parts = sortExpression.Split(' '); bool descending = false; string property = ""; if (parts.Length > 0 && parts[0] != "") { property = parts[0]; if (parts.Length > 1) { descending = parts[1].ToLower().Contains("esc"); } PropertyInfo prop = typeof(T).GetProperty(property); if (prop == null) { throw new Exception("No property '" + property + "' in + " + typeof(T).Name + "'"); } if (descending) return list.OrderByDescending(x => prop.GetValue(x, null)); else return list.OrderBy(x => prop.GetValue(x, null)); } return list; }
public void Test() { var list = new List<Customer>(); list.OrderBy("Name desc"); } public class Customer { public string Name { get; set; } }
是不是很实用呀,这个来自一个名叫http://www.extensionmethod.net/ 网站.希望对您有帮助.
Author:Petter http://wintersun.cnblogs.com