c# - 按一个元素排序并在同一个 LINQ 查询中返回多个属性
问题描述
我有这个list
List<Order> OL = new List<Order>()
{
new Order("O-1","P1",200,2),
new Order("O-2","P1",200,3),
new Order("O-3","P1",1000,1),
new Order("O-4","P2",200,2)
};
订单 class
:_
class Order
{
public string ID { get; set; }
public string Product { get; set; }
public int Price { get; set; }
public int Quantity { get; set; }
public int Total { get { return Price * Quantity; } }
public Order(string _ID, string _Product, int _Price, int _Quantity)
{
ID = _ID;
Product = _Product;
Price = _Price;
Quantity = _Quantity;
}
public Order()
{
}
}
所以我想返回每个产品的名称和计数(产品在订单中重复的次数)。
我试过 :
var P = OL.OrderByDescending(x => x.Product.Count()).Take(2);
MessageBox.Show(P.ElementAt(0).Product);
但只是得到产品名称,请帮助?并提前感谢。
解决方案
怎么样:
var groupedProducts = OL.GroupBy(o => o.Product)
.Select(g => new { Product = g.Key, Quantity = g.Count() })
.OrderByDescending(p => p.Quantity);
推荐阅读
- angular - How to make input readonly, but still allow some keys to work
- javascript - 剑道网格导出到 Excel 下拉列表值而不是导出文件中的文本
- asp.net - 在 .NET 上使用 https 上传多个图像的问题
- postgresql - docker-compose - Spring boot 不会连接到 postgres,除非 network_mode: host
- java - 静态资源的编码问题
- c# - C# Debug build ok,但 Release build 由于优化而失败
- mysql - query.conf 上的双 acctupdateinterval(临时更新部分)
- java - Undefined method type
- docker - 如何根据分支名称更改 Jenkins 中的代理标签
- php - 如何在 woocommerce 订单编辑器中添加自定义项目