我正在尝试使用查询语法来遍历对象列表,并选择其UnitPrice属性的int最低的对象。
var lowPrice = from l in DataLoader.LoadProducts()
group l by l.Category into newGroup
select new
{
cat = newGroup.Key,
lowest = from p in newGroup
where p.UnitPrice < p.UnitPrice
select p
};
上面的代码应在UnitPrice属性中选择一个值最低的对象并将其存储到最低属性中。
但是我不知道选择单价最低的对象的正确语法。
这是我的产品对象的示例。有很多同类产品。我的目标是显示类别名称和该类别下单价最低的产品。我相信总共有6个类别。
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",
UnitPrice = 22.0000M,
UnitsInStock = 53
},
答案 0 :(得分:0)
如果您要选择每个类别中价格最低的单个对象,请采用以下解决方案:
var lowestPriceCategories = DataLoader.LoadProducts()
.GroupBy(x => x.Category)
.Select(x => new
{
Category = x.Key,
LowestPrice = x.OrderBy(y => y.UnitPrice).FirstOrDefault()
});
答案 1 :(得分:0)
感谢您的支持。我能够使用大家提出的建议创建自己认为需要的东西。
var lowPrice = from l in DataLoader.LoadProducts()
group l by l.Category into newGroup
select new
{
cat = newGroup.Key,
lowest = (from p in newGroup
orderby p.UnitPrice
select p).First()
};
结果
foreach (var p in lowPrice)
{
Console.WriteLine($"{p.cat} {p.lowest.ProductName}");
}