1

I have a class like this

         class car   
           {
             public string carName { get; set; }
             public decimal price { get; set; }//Group id
           }

         I have two lists like this

         List<car> listCars = new List<car>();
         List<car> lowest = new List<car>();

I want to search for the car with lowest price in the listCars list and add the lowest price car object to the list lowest.

      var minPrice = lstCars.Min(carobj=>carobj.price);

but in this you get only the minimum car price only. I want to get the car object and add it to the lowest list. How to do that?

user3572467
  • 59
  • 1
  • 1
  • 8

3 Answers3

2

You can sort your cars based on Price in ascending order, then get the first car which has the lowest price:

lowest.Add(listCars.OrderBy(car => car.price).First());

You can also use MinBy method, it would be more efficient for bigger lists because ordering is expensive.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

Multiple ways of doing it. You can use OrderBy and then select First or you can use your already deteremined minPrice like:

var minPrice = lstCars.Min(carobj=>carobj.price);
lowest.Add(listCars.FirstOrDefault(r=> r.price == minPrice));
Habib
  • 219,104
  • 29
  • 407
  • 436
0

Lowest price which is string? Is this a price, then i would use decimal. If you also want to add all cars with the lowest price:

var minPriceGroup = listCars
    .Select(c => new { Car = c, Price = decimal.Parse(c.price) })
    .OrderBy(x => x.Price)
    .GroupBy(x => x.Price)
    .First();
lowest.AddRange(minPriceGroup.Select(x => x.Car));
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939