首页 > 解决方案 > 按一个元素排序并在同一个 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);

但只是得到产品名称,请帮助?并提前感谢。

标签: c#linq

解决方案


怎么样:

var groupedProducts = OL.GroupBy(o => o.Product)
                     .Select(g => new { Product = g.Key, Quantity = g.Count() })
                     .OrderByDescending(p => p.Quantity);

推荐阅读