Reputation: 97
I have this 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)
};
The Order 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()
{
}
}
So I want to return the name and the counting (Number of times the product repeated in orders) for each product.
I tried :
var P = OL.OrderByDescending(x => x.Product.Count()).Take(2);
MessageBox.Show(P.ElementAt(0).Product);
But just getting the product name, Please any help? and thanks in advance.
Upvotes: 1
Views: 48
Reputation: 32740
How about:
var groupedProducts = OL.GroupBy(o => o.Product)
.Select(g => new { Product = g.Key, Quantity = g.Count() })
.OrderByDescending(p => p.Quantity);
Upvotes: 2
Reputation: 13652
Group by Product
then sort by Count()
var P = OL.GroupBy(x => x.Product)
.OrderByDescending(x => x.Count())
.Select(g => new { Product = g.Key, Count = g.Count() });
Upvotes: 1