我需要使用 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 的列表的方法。 例如,我能够单独获取“饮料”类别中的产品数量,但这样我必须创建与类别一样多的查询...(不好)..
int query = listProd.Where(p => p.Category == "Beverages").Count();
所以我想要的是创建这样的查询:
Category, count(属于该Category的产品)
饮料,5
调味品,7
最佳答案
您可以使用此 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() });
关于c# - 使用 Lambda 或经典表达式使用 LinQ 列出类别及其产品数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45452838/