Gassi
Gassi

Reputation: 1

Finding specific item in a list using LINQ

So I am learning the basics of LINQ and I´m haveing a little trouble.

I have a list:

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;
    }

Using LINQ I am suppost to find the highest priced product that is also less than or equal to 120 (highest price under 120). The hint that I am given is: filter the products based on price, order the result, and then return the first one.

The LINQ I have now is:

var result = GetProducts().OrderBy(y => y.Price).Last();

This only gives me the highest priced product so I need to add a filter before or after I use the OrderBy. Been trying this and that with no luck. If anyone could give me more hints or be of some assistance would be greatly appreciated

Upvotes: 0

Views: 189

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

I would make two changes:

  1. Use OrderByDescending() so that the element you want is near the front of the result, not the end.
  2. Add your < 120 filter to the query.

That might look like this:

var result = GetProducts().OrderByDescending(y => y.Price).First(y => y.Price < 120);

Upvotes: 1

Related Questions