首頁 > 後端開發 > C#.Net教程 > C#中如何使用order by、group by?

C#中如何使用order by、group by?

王林
發布: 2023-08-31 21:45:02
轉載
1399 人瀏覽過

C#中如何使用order by、group by?

Order by 用於對陣列進行升序或降序排序

GroupBy 運算子屬於分組運算子類別。此運算子採用扁平的項目序列,根據特定鍵將該序列組織為群組 (IGrouping),並傳回序列群組

範例

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() {
      //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 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() {
      //Order by
      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
登入後複製

以上是C#中如何使用order by、group by?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板