所以我正在学习LINQ的基础知识,我遇到了一些麻烦。
我有一个清单:
public static IEnumerable<Product> GetProducts()
{
List<Product> products = new List<Product>();
products.Add(new Product { Name = "Milk", Price = 90, CategoryID = 4, ID = 1 });
products.Add(new Product { Name = "Cheese", Price = 130, CategoryID = 4, ID = 2 });
products.Add(new Product { Name = "Butter", Price = 110, CategoryID = 4, ID = 3 });
products.Add(new Product { Name = "Beetroot juice", Price = 300, CategoryID = 1, ID = 6 });
products.Add(new Product { Name = "Carrot juice", Price = 190, CategoryID = 1, ID = 7 });
products.Add(new Product { Name = "Ginger ale", Price = 990, CategoryID = 1, ID = 8 });
products.Add(new Product { Name = "Oregano", Price = 500, CategoryID = 2, ID = 9 });
products.Add(new Product { Name = "Salt", Price = 550, CategoryID = 2, ID = 10 });
products.Add(new Product { Name = "Pepper", Price = 490, CategoryID = 2, ID = 11 });
return products;
}
使用LINQ我希望找到价格最高的产品,其价格也小于或等于120(120以下的最高价格)。我给出的提示是:根据价格过滤产品,订购结果,然后返回第一个。
我现在拥有的LINQ是:
var result = GetProducts().OrderBy(y => y.Price).Last();
这只给了我最高价的产品,所以我需要在使用OrderBy之前或之后添加一个过滤器。一直在尝试这个,没有运气。如果有人能给我更多提示或者得到一些帮助,将不胜感激
答案 0 :(得分:1)
我会做两处修改:
OrderByDescending()
,以便您想要的元素靠近结果的前面,而不是结尾。< 120
过滤器添加到查询中。这可能是这样的:
var result = GetProducts().OrderByDescending(y => y.Price).First(y => y.Price < 120);