
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<K,V>) based on a specific key and return groups of sequence
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
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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号