简体   繁体   English

如何从列表中找到最小值?

[英]How to find the lowest value from the list?

 //create the new object for cars
    Cars s1 = new Cars("Toyota", 2005, 500000, "White", "good");//Car1 Ob
    Cars s2 = new Cars("Honda", 2004, 550000, "Black", "fine");//Car2 Ob
    Cars s3 = new Cars("Nissen", 2012, 490000, "Yellow", "best");//Car3 Ob
    Cars s4 = new Cars("Suzuki", 2012, 390000, "Blue", "fine");//Car4 Ob
    Cars s5 = new Cars("BMW", 2012, 1000000, "Green", "Good");//Car5 Ob

    //Create list to add objects into the memory
    List<Cars> list1 = new List<Cars>();
    list1.Add(s1);list1.Add(s2);list1.Add(s3);list1.Add(s4);list1.Add(s5);



 //cars info which has the lowest price
        double lowest_price = 0;
        foreach(Cars a in list1){
        if(a.price <= lowest_price){
            lowest_price = a.price;
            Console.WriteLine(a.price);
            }
        }//end of loop

That's the code which I am trying to print out the the cars info which has the lowest price.这是我试图打印出价格最低的汽车信息的代码。 But nothing gets print out.但没有打印出来。

Use the LINQ Min extension method:使用LINQ Min扩展方法:

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".此外,您没有指定,但如果您的集合中没有汽车且InvalidOperationException指示“序列不包含元素”,则此操作将失败。 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 .至于为什么您当前的代码不打印任何内容,这是因为您的初始值为0 No car has a value that is negative (or less than 0 ).没有汽车具有负值(或小于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 .请注意,这有额外的副作用,如果你的list1车是空的,那么lowest_price值将是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:如果是关注点,没有车需要返回0 ,可以稍微调整一下:

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

您将使用列表中的 Min 扩展名。

lowest_price = list1.Min(c => c.price);

just based on the problem with your code: you are not going to have a lower price than 0... so you need change it to:仅基于您的代码问题:您的价格不会低于 0...所以您需要将其更改为:

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

Edit : this will only work if list1 exists and isn't empty, for general use you'd need to check if (list1 is null || list1.Count==0) first line.编辑:这仅在list1存在且不为空时才有效,对于一般用途,您需要检查if (list1 is null || list1.Count==0)第一行。

If you want to fix your code to work (instead of using Linq - which is the recommended approach), change this line:如果要修复代码以使其正常工作(而不是使用 Linq - 这是推荐的方法),请更改以下行:

double lowest_price = 0;

to this:对此:

double lowest_price = double.MaxValue;

The other responses correctly provide a LINQ solution, but the issue with your specific code is that you are checking if the car's priced (a.price) is <= your lowest_price variable.其他响应正确地提供了 LINQ 解决方案,但您的特定代码的问题在于您正在检查汽车的价格 (a.price) 是否 <= 您的最低价格变量。 Your lowest_price variable is instantiated with a value of 0 and according to your default car prices listed which are all greater than 0, will never validate.您的最低价格变量被实例化为 0 值,并且根据您列出的默认汽车价格,这些价格都大于 0,永远不会验证。 So your lowest_price variable will never be updated and therefore never write it's value to the console.因此,您的最低价格变量永远不会更新,因此永远不会将其值写入控制台。 That's what's causing your request of "nothing prints out".这就是导致您要求“没有打印输出”的原因。 It's an error in your check and in your logic.这是你的支票和你的逻辑错误。 Update that line to "if (lowest_price <= a.price)" to get closer.将该行更新为“if (lowest_price <= a.price)”以接近。

public  static int FindMin(IEnumerable<int> numbers)
    {
        Expression<Func<int, int, int>> expression = (left, right) => left < right ? left : right;
        InvocationExpression invoker = Expression.Invoke(expression,
                                   Expression.Constant(numbers.First())
                                  , Expression.Constant(numbers.ToList()[1]));

        foreach (int number in numbers.Skip(2))
        {
            invoker = Expression.Invoke(expression,
                               invoker,
                               Expression.Constant(number));
        }
        var lambdaExpression = Expression.Lambda<Func<int>>(invoker);
        Console.WriteLine($"Expression call tree:{lambdaExpression.ToString()}");
        return lambdaExpression.Compile().Invoke();
    }
}
var result = list1.Where((x) => x.price== list1.Min(y => y.price)).ToList();

This will return car info with the lowest price.这将返回最低价格的汽车信息。 Add reference using System.Linq; using System.Linq;添加引用using System.Linq;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM