public class Product { public string Name { get; set; } public int CategoryID { get; set; } } public class Category { public string Name { get; set; } public int ID { get; set; } }
static List<Category> categories = new List<Category>() { new Category(){Name="Beverages", ID=001}, new Category(){Name="Condiments", ID=002}, new Category(){Name="Vegetables", ID=003}, new Category(){Name="Grains", ID=004}, new Category(){Name="Fruit", ID=005}, new Category(){Name="Other", ID=006} }; static List<Product> products = new List<Product>() { new Product{Name="Cola", CategoryID=001}, new Product{Name="Tea", CategoryID=001}, new Product{Name="Mustard", CategoryID=002}, new Product{Name="Pickles", CategoryID=002}, new Product{Name="Carrots", CategoryID=003}, new Product{Name="Bok Choy", CategoryID=003}, new Product{Name="Peaches", CategoryID=005}, new Product{Name="Melons", CategoryID=007}, };
l 使用排序
1. 使用排序时使用的显示语句
foreach (var c in orderByResult) Console.WriteLine("ID={0},Name={1}", c.ID, c.Name);
表达式
var orderByResult = from c in categories orderby c.ID //默认为升序,也可以在后面加上ascending select c; // 方法 var orderByResult = categories.OrderBy(c=>c.ID);
表达式
var orderByResult = from c in categories orderby c.ID descending select c; // 方法 var orderByResult = categories.OrderByDescending(c=>c.ID);
4. 多个属性的升序
表达式
var orderByResult = from c in categories orderby c.ID,c.Name select c; //方法 var orderByResult = categories.OrderBy(c=>c.ID).ThenBy(c=>c.Name);
表达式
var orderByResult = from c in categories orderby c.ID, c.Name descending select c; //方法 var orderByResult = categories.OrderByDescending(c=>c.ID).ThenByDescending(c=>c.Name);
延伸阅读
文章来源于领测软件测试网 https://www.ltesting.net/