Reputation: 4402
Im facing a problem with sorting lists where im trying to find the cheapest value. The sorting is not the problem, its the values returned that are the problem and the condition i want to meet.
Basically I may have 0 values in my results set, this is because these items have been temporarily put on hold and as such they dont hold a value but quotes still arrive for them.
The idea was to sort the results by total value and then take the first item in the list which in theory would be the cheapest.
void Main()
{
GetCheapest();
}
public void GetCheapest()
{
List<Car> numbers = new List<Car>
{
new Car() { Type="dearest", Total = 990 },
new Car() { Type="", Total = 570 },
new Car() { Type="", Total = 907 },
new Car() { Type="cheapest", Total = 0 },
new Car() { Type="", Total = 333 },
new Car() { Type="", Total = 435 },
new Car() { Type="", Total = 435 }
};
//order ascending
IEnumerable<Car> query = numbers.OrderBy( q => q.Total );
//set the cheapest to be the first index in the sorted IEnumerable
var cheapest = query.First();
//output the cheapest
Console.Write( cheapest.Type + " - £" + cheapest.Total + ", Winning!!" );
//new line
Console.WriteLine( Environment.NewLine );
//output each one
foreach( Car q in query )
{
Console.WriteLine( q.Type + " - £" + q.Total );
}
}
//Quote Object
public class Car
{
public decimal Total { get; set; }
public string Type { get; set; }
}
In summary I would like to iterate through the returned list until I reach an index which holds a value greater than 0.
The answer to the example given would be 333.
If anyone has any better ideas of doing this im open to trying them.
I have looked at these questions on SO so far which dont yield an answer:
use LINQ to find the product with the cheapest value?
Get object with minimum value using extension method min()
Upvotes: 0
Views: 3055
Reputation: 72165
If you want to find a way to process an already sorted list of values:
IEnumerable<Car> query = numbers.OrderBy( q => q.Total );
skip all 0s, then take the first element:
var cheapest = query.SkipWhile(x => x == 0).First();
Upvotes: 2
Reputation: 152521
Unless I'm missing something it would just be:
numbers.Where(c => c.Total > 0)
.OrderBy(c => c.Total)
.First();
or to chain to your existing query:
IEnumerable<Car> query = numbers.OrderBy( q => q.Total );
var cheapestCar =
query.Where(c => c.Total > 0)
.First();
Upvotes: 7
Reputation: 3290
int cheapest = numbers.Where(c=>c.Total > 0).Min(c=>c.Total);
will get you the minimum price greater than 0 in the list.
The where clause removes anything with a total <= 0 from the list. The min call returns the smallest remaining value.
If you would rather have the whole object rather than just the price, use
var cheapest = numbers.OrderBy(c=>c.Total).First(c=>c.Total > 0);
Upvotes: 3