我需要使用LinQ lambda或经典表达式列出属于每个类别的产品的类别和计数。
这是班级:
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; }
}
这是我用来确定列表外观的列表。
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..
我有一个返回名为listProd的列表的方法。 例如,我能够在&#34; Beverages&#34;中获得产品数量。单独的类别,但这样我必须创建尽可能多的查询类别...(不好)..
int query = listProd.Where(p => p.Category == "Beverages").Count();
所以我想要的是创建这样的查询:
类别,计数(属于该类别的产品)
饮料,5
调味品,7
答案 0 :(得分:4)
您可以使用此LINQ查询
var result = productList.GroupBy(x => x.Category)
.Select(y => new { Category = y.Key, Count = y.Count() });
按类别分组,然后使用Key
和Count()
获取结果对象。
根据您提供的样本数据,结果将如下所示
如果您想获得有关LINQ的更多信息和示例,我建议101 LINQ Samples。
修改强>
根据您的评论:
您可以使用Where
语句仅获取包含4个以上产品的类别。
var result = productList.GroupBy(x => x.Category)
.Where(x => x.Count() > 4)
.Select(y => new { Category = y.Key, Count = y.Count() });= y.Count() });
答案 1 :(得分:3)
使用以下和平代码
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() });