![](/img/trans.png)
[英]How to find three largest and three smallest decmicals using Math.Max, Math.Min
[英]How can I get the largest, and smallest number from a list using LINQ, without using Min() Max()?
我一直在开发一个生成纬度和经度的应用程序,我现在需要能够找到最大值和最小值来确定数据集的上限和下限(以及东/西限制)。
我一直在尝试使用 Enumerable.Min 方法对它们进行排序,但它似乎不支持低于 -100.0000 的数字。
我的代码有误吗? 如何以最有效的方式获得最大和最小的数字(列表有大约 150,000 多个条目)。
public static void Main()
{
var arr = new string[]{"-88.98559", "-94.98711", "-95.79591", "-98.04622", "100.0001", "-101.57691", "-110.00614"};
var arrList = new List<string>(){};
foreach (var value in arr)
{
arrList.Add(value);
}
Console.WriteLine(arrList.Min().ToString()); //Result : 100.0001, should be -110.00614
Console.WriteLine(arrList.Max().ToString()); //Result : -98.04622
}
看起来您的问题是您在字符串值上使用了最小值/最大值。 如果您比较字符串“100”与“90”,则“100”较小,因为 1 < 9。(与“alice”与“bob”没有区别。a < b 即使“bob”更短)如果您想要进行数字比较,那么你必须让 arrList 成为一个浮点数或其他东西的数组,并在添加到列表之前使用float.parse(value)
。
当然,简单的答案是将我的值存储为双精度值(并调整我的生成代码以不转换为字符串)。 谢谢大家的鼓励!
public static void Main()
{
var arr = new double[]{-88.98559, -94.98711, -95.79591, -98.04622, 100.0001, -101.57691, -110.00614};
var arrList = new List<double>(){};
foreach (var value in arr)
{
arrList.Add(value);
}
Console.WriteLine(arrList.Min().ToString());
Console.WriteLine(arrList.Max().ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.