Reputation: 190
I need to list the categories and the count of the products that belong to each category using LinQ lambda or classic expressions.
This is the Class:
class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string Category { get; set; }
public decimal UnitPrice { get; set; }
public int UnitsInStock { get; set; }
}
This is the list I am using just to figure out how the list looks like.
IEnumerable<Product> productList = new List<Product> {
new Product { ProductID = 1, ProductName = "Chai", Category = "Beverages",
UnitPrice = 18.0000M, UnitsInStock = 39 },
new Product{ ProductID = 2, ProductName = "Chang", Category = "Beverages",
UnitPrice = 19.0000M, UnitsInStock = 17 },
new Product{ ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments",
UnitPrice = 10.0000M, UnitsInStock = 13 },
new Product{ ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments",......and so on..
I have a method that returns a list called listProd. For instance, I am able to get the count of products in "Beverages" category individually, but this way I have to create as many queries as Categories are...(not good)..
int query = listProd.Where(p => p.Category == "Beverages").Count();
So what I want is to create query something like this:
Category, count(products that belongs to the Category)
Beverages, 5
Condiments, 7
Upvotes: 1
Views: 2270
Reputation: 6155
You could use this LINQ query
var result = productList.GroupBy(x => x.Category)
.Select(y => new { Category = y.Key, Count = y.Count() });
First group by the category and then use Key
and Count()
to get the result objects.
With the sample data you've provided the result will look like
If you want to get more information and samples about LINQ I recommend 101 LINQ Samples.
edit
Accoring to your comment:
You could use the Where
statement to get only categorie which have more than 4 products.
var result = productList.GroupBy(x => x.Category)
.Where(x => x.Count() > 4)
.Select(y => new { Category = y.Key, Count = y.Count() });= y.Count() });
Upvotes: 4
Reputation: 869
Use the following peace code
IEnumerable<Product> productList = new List<Product> {
new Product { ProductID = 1, ProductName = "Chai", Category = "Beverages",
UnitPrice = 18.0000M, UnitsInStock = 39 },
new Product{ ProductID = 2, ProductName = "Chang", Category = "Beverages",
UnitPrice = 19.0000M, UnitsInStock = 17 },
new Product{ ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments",
UnitPrice = 10.0000M, UnitsInStock = 13 },
new Product{ ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments"}
};
var list = (from x in productList
group x.Category by x.Category into g
select new { Category = g.Key, Count = g.Count() });
Upvotes: 3