要按类别划分产品列表,请使用不带foreach的LINQ



如何在没有foreach的方法中返回值?我的意思是,我可以很容易地将其划分为foreach循环,但我需要得到IEnumerable<(string category, IEnumerable<string> productsName)>格式的答案。我能做什么?

public static IEnumerable<(string category, IEnumerable<string> productsName)> GroupByCategory()
{
List<Product> products = Products.ProductList;
var orderGroups = products.Where(p => p.ProductId <= 20).GroupBy(p => p.Category,
(Key, g) => new { Category = Key, Products = g });
foreach (var i in orderGroups)
{
Console.WriteLine($"Category={i.Category}:");
foreach (var p in i.Products)
{
var s = $"ProductID={p.ProductId},
Product Name={p.ProductName},
UnitPrice={p.UnitPrice},
UnitsInStock={p.UnitsInStock}";
Console.WriteLine(s);
}
}
}

这样的东西可能对你有用。特别是select和嵌套的select语句。

public IEnumerable<(string category, IEnumerable<string> productsName)> GroupByCategory()
{
List<Product> products = Products.ProductList;
return products.Where(p => p.ProductId <= 20)
.GroupBy(p => p.Category)
.Select(g => (g.Key, g.Select(p => p.ProductName)));
}

就我个人而言,我会创建一个模型来更好地封装结果,比如CategoryGroup。然后,您可以为它构建一个构造函数,它将IGrouping<string, Product>作为参数来进一步清理.Select,但这只是首选!

最新更新