C# 如何从列表中找到最小值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17658907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the lowest value from the list?
提问by user2042721
//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.
这是我试图打印出价格最低的汽车信息的代码。但没有打印出来。
回答by Chris Sinclair
Use the LINQ Minextension method:
使用LINQMin扩展方法:
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 InvalidOperationExceptionindicating "Sequence contains no elements". If it's possible you have no cars, a quick update might be:
此外,您没有指定,但如果您的集合中没有汽车并InvalidOperationException指示“序列不包含元素” ,则此操作将失败。如果您可能没有汽车,快速更新可能是:
double lowest_price = list1.Any() ? list1.Min(car => car.price) : 0;
As to why your currentcode 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:
至于为什么您当前的代码不打印任何内容,是因为您的初始值为0. 没有汽车具有负值(或小于0)。如果要继续使用现有循环,请将初始值更改为可能的最高值:
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 list1of cars is empty, then the lowest_pricevalue will be Double.MaxValue. This may or may not be a concern for you with your existing code.
请注意,这有额外的副作用,如果您list1的汽车为空,则lowest_price值将为Double.MaxValue. 对于您现有的代码,这可能是也可能不是您的问题。
If it is a concern, and needto return 0if 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;
}
回答by KingPancake
You would use the Min extension on the list.
您将使用列表中的 Min 扩展名。
lowest_price = list1.Min(c => c.price);
回答by Bolu
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 list1exists 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)第一行。
回答by Gary Richter
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. 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. 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.
其他响应正确地提供了 LINQ 解决方案,但您的特定代码的问题在于您正在检查汽车的价格 (a.price) 是否 <= 您的最低价格变量。您的最低价格变量被实例化为 0 值,并且根据您列出的默认汽车价格,这些价格都大于 0,永远不会验证。因此,您的最低价格变量永远不会更新,因此永远不会将其值写入控制台。这就是导致您要求“没有打印输出”的原因。这是你的支票和你的逻辑错误。将该行更新为“if (lowest_price <= a.price)”以接近。
回答by ytoledano
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;
回答by dot.net5000
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();
}
}

