
Order by is used to sort the arrays in the ascending or in the descending order
GroupBy operator belong to Grouping Operators category. This operator takes a flat sequence of items, organize that sequence into groups (IGrouping) based on a specific key and return groups of sequence
Example
class ElectronicGoods { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public static List GetElectronicItems() { return new List() { 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() { //Group by 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(); }}
Output
Phone - 2----------LandLine PhoneMobile PhoneTV - 1----------Television TVFood - 2----------Grinder FoodMixer Food
Order By
的翻译为:
按顺序排列
class ElectronicGoods { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public static List GetElectronicItems() { return new List() { 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() { //Order by var res = ElectronicGoods.GetElectronicItems().OrderBy(x => x.Category); foreach (var items in res) { Console.WriteLine(items.Name + "t" + items.Category); } Console.ReadKey(); }}
Output
Grinder FoodMixer FoodMobile PhoneLandLine PhoneTelevision TV
以上就是C#中如何使用order by、group by?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1435110.html
微信扫一扫
支付宝扫一扫


