Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để sử dụng thứ tự theo, nhóm theo trong c #?

Order by được sử dụng để sắp xếp các mảng theo thứ tự tăng dần hoặc giảm dần

Toán tử GroupBy thuộc danh mục Toán tử Nhóm. Toán tử này lấy một chuỗi các mục bằng phẳng, tổ chức chuỗi đó thành các nhóm (IGrouping ) dựa trên một khóa cụ thể và trả về các nhóm của chuỗi

Ví dụ

 class ElectronicGoods {public int Id {get; đặt; } public string Tên {get; đặt; } public string Category {get; đặt; } public static List  GetElectronicItems () {return new List  () {new ElectronicGoods {Id =1, Name ="Mobile", Category ="Phone"}, ElectronicGoods mới {Id =2, Name =" LandLine ", Category =" Phone "}, ElectronicGoods mới {Id =3, Name =" TV ", Category =" TV "}, ElectronicGoods mới {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 (); }} 

Đầu ra

 Phone - 2 ---------- LandLine PhoneMobile PhoneTV - 1 ---------- TV TVFood - 2 ---------- Grinder FoodMixer Food  

Đặt hàng theo

 class ElectronicGoods {public int Id {get; đặt; } public string Tên {get; đặt; } public string Category {get; đặt; } public static List  GetElectronicItems () {return new List  () {new ElectronicGoods {Id =1, Name ="Mobile", Category ="Phone"}, ElectronicGoods mới {Id =2, Name =" LandLine ", Category =" Phone "}, ElectronicGoods mới {Id =3, Name =" TV ", Category =" TV "}, ElectronicGoods mới {Id =4, Name =" Grinder ", Category =" Food "}, new ElectronicGoods {Id =5, Name ="Mixer", Category ="Food"},}; }} class Program {static void Main () {// Đặt hàng theo var res =ElectronicGoods.GetElectronicItems (). OrderBy (x => x.Category); foreach (var items in res) {Console.WriteLine (items.Name + "\ t" + items.Category); } Console.ReadKey (); }} 

Đầu ra

 Máy xay thực phẩmMixer thực phẩmĐiện thoại di độngĐiện thoại đường dâyTTV truyền hình