首页  >  文章  >  后端开发  >  C#中如何使用order by、group by?

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

王林
王林转载
2023-08-31 21:45:021357浏览

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();
   }
}

输出

Phone - 2
----------
LandLine Phone
Mobile Phone
TV - 1
----------
Television TV
Food - 2
----------
Grinder Food
Mixer Food

Order By

的翻译为:

按顺序排列

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删除