[英]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.