C# 列出类别和it';s使用Lambda或经典表达式的LinQ产品计数
我需要使用LinQ lambda或classic表达式列出属于每个类别的类别和产品数量 这是一节课:C# 列出类别和it';s使用Lambda或经典表达式的LinQ产品计数,c#,linq,lambda,C#,Linq,Lambda,我需要使用LinQ lambda或classic表达式列出属于每个类别的类别和产品数量 这是一节课: class Product { public int ProductID { get; set; } public string ProductName { get; set; } public string Category { get; set; } public decimal UnitPrice { get; s
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..
所以我想创建如下查询:
类别,计数(属于该类别的产品)
饮料,5
调味品,7使用以下和平代码
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() });
IEnumerable productList=新列表{
新产品{ProductID=1,ProductName=“Chai”,Category=“饮料”,
单价=18.0000M,单位库存=39},
新产品{ProductID=2,ProductName=“Chang”,Category=“饮料”,
单价=19.0000M,单位库存=17},
新产品{ProductID=3,ProductName=“茴香糖浆”,Category=“调味品”,
单价=10.0000M,单位库存=13},
新产品{ProductID=4,ProductName=“厨师安东的卡津调味品”,Category=“调味品”}
};
变量列表=(从productList中的x开始)
将x.类别按x.类别分组为g
选择新{Category=g.Key,Count=g.Count()});
您可以使用此LINQ查询
var result = productList.GroupBy(x => x.Category)
.Select(y => new { Category = y.Key, Count = y.Count() });
首先按类别分组,然后使用键
和计数()
获取结果对象
使用您提供的示例数据,结果如下所示
如果你想得到更多关于LINQ的信息和样品,我推荐
编辑
根据您的评论:
您可以使用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() });
请查看仅列出包含4种以上产品的类别的限制条件如何?我试图通过101个LINQ样本来找出答案。我是一个新手,似乎我还有很长的路要走
var result = productList.GroupBy(x => x.Category)
.Where(x => x.Count() > 4)
.Select(y => new { Category = y.Key, Count = y.Count() });= y.Count() });