订购用于按升序或降序对数组进行排序
GroupBy运算符属于“分组运算符”类别。该运算符采用扁平的项目序列,根据特定键将该序列组织为组(IGrouping <K,V>),并返回序列组
class ElectronicGoods { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public static List<ElectronicGoods> GetElectronicItems() { return new List<ElectronicGoods>() { new ElectronicGoods { Id = 1, Name = "Mobile", Category = "Phone"}, new ElectronicGoods { Id = 2, Name = "LandLine", Category = "Phone"}, new ElectronicGoods { Id = 3, Name = "Television", Category = "TV"}, new ElectronicGoods { Id = 4, Name = "Grinder", Category = "Food"}, new ElectronicGoods { Id = 5, Name = "Mixer", Category = "Food"}, }; } } class Program { static void Main() { //分组 var res=ElectronicGoods.GetElectronicItems().GroupBy(x => x.Category).Select(x => new { Key = x.Key, electronicGoods = x.OrderBy(c => c.Name) }); foreach (var group in res) { Console.WriteLine("{0} - {1}", group.Key, group.electronicGoods.Count()); Console.WriteLine("----------"); foreach (var electronicGoods in group.electronicGoods) { Console.WriteLine(electronicGoods.Name + "\t" + electronicGoods.Category); } Console.WriteLine(); Console.WriteLine(); } Console.ReadKey(); } }
输出结果
Phone - 2 ---------- LandLine Phone Mobile Phone TV - 1 ---------- Television TV Food - 2 ---------- Grinder Food Mixer Food
class ElectronicGoods { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public static List<ElectronicGoods> GetElectronicItems() { return new List<ElectronicGoods>() { new ElectronicGoods { Id = 1, Name = "Mobile", Category = "Phone"}, new ElectronicGoods { Id = 2, Name = "LandLine", Category = "Phone"}, new ElectronicGoods { Id = 3, Name = "Television", Category = "TV"}, new ElectronicGoods { Id = 4, Name = "Grinder", Category = "Food"}, new ElectronicGoods { Id = 5, Name = "Mixer", Category = "Food"}, }; } } class Program { static void Main() { //订购 var res = ElectronicGoods.GetElectronicItems().OrderBy(x => x.Category); foreach (var items in res) { Console.WriteLine(items.Name + "\t" + items.Category); } Console.ReadKey(); } }
输出结果
Grinder Food Mixer Food Mobile Phone LandLine Phone Television TV