How to find the lowest value from the list?

Use the LINQ Min extension method:

double lowest_price = list1.Min(car => car.price);

Also, you didn’t specify, but this will fail if you have no cars in your set with an InvalidOperationException indicating “Sequence contains no elements”. If it’s possible you have no cars, a quick update might be:

double lowest_price = list1.Any() ? list1.Min(car => car.price) : 0;

As to why your current code prints nothing it’s because your initial value is 0. No car has a value that is negative (or less than 0). If you want to keep using your existing loop, change the initial value to the highest possible value:

double lowest_price = Double.MaxValue;
foreach(Cars a in list1){
    if(a.price <= lowest_price){
        lowest_price = a.price;
        Console.WriteLine(a.price);
    }
}//end of loop

Note that this has the additional side effect that if your list1 of cars is empty, then the lowest_price value will be Double.MaxValue. This may or may not be a concern for you with your existing code.

If it is a concern, and need to return 0 if there are no cars, you can make a slight adjustment:

double lowest_price;
if (list1.Any()){
    lowest_price = Double.MaxValue;
    foreach(Cars a in list1){
        if(a.price <= lowest_price){
            lowest_price = a.price;
            Console.WriteLine(a.price);
        }
    }//end of loop
}
else{
    lowest_price = 0;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)