使用 Linq 查找具有负数的数字序列的最小值

Find the minimum of a number sequence with negative numbers with Linq

以下代码没有给出预期的最小值 -1。相反,我得到 0。 你知道为什么吗?

class MainClass
{
    public static void Main (string[] args)
    {
        string numbers = "-1 0 1 2 3 4 5";
        Console.WriteLine (numbers.Split (' ')[0]);     // output: -1
        string max = numbers.Split(' ').Max();
        string min = numbers.Split(' ').Min();
        Console.WriteLine("{0} {1}", max, min);         // output: "5 0"
    }
}

它是一个字符串,因此从字符串中获取最大值与从数字中获取最大值完全不同。例如,如果您有一个如下所示的数组

char[] someCharArray = new char[] { '1', '12', '2' }

在此数组上调用 Max() 会得到 2,因为 2 在字符串顺序中 "higher" 而不是 12。

考虑来自 string/char 的 Max/Min 值 您需要考虑字母顺序。如果您有字母 A-Z 的集合,调用 Min() 将 return A,调用 Max() 将 return Z.

要按数字顺序获得 Max/Min 您需要转换为某种数字类型,例如 int。 见下文:

string numbers = "-1 0 1 2 3 4 5";
int min = numbers.Split(' ').Select(x => int.Parse(x)).Min();
Console.WriteLine(min); // gives You -1

我还没有完全定义答案,但似乎是因为 - 没有被考虑在内.. 你可以用 CompareOrdinal

来确认
    Console.WriteLine(String.CompareOrdinal("-1", "0"));  // -3 meaning -1 min
    Console.WriteLine(String.Compare("-1", "0"));  // 1 meaning 0 min

无论哪种方式,您都在尝试比较数字,因此您应该将它们视为数字,以免出现相似的细微差别。


尝试解释...

字符串实现 IComparable<string> 所以 String.Min uses that implementation (see remarks). Which in turn uses CompareTo,

现在在这个方法的注释中

Character sets include ignorable characters. The CompareTo(String) method does not consider such characters when it performs a culture-sensitive comparison. For example, if the following code is run on the .NET Framework 4 or later, a comparison of "animal" with "ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent.

(强调我的)

如你所见。 - 被忽略,因此在 ascii table 中具有较小值的 0 用于比较

这种行为有两个原因:

  1. 您正在对字符串而不是数字进行排序。这意味着在幕后,Linq 正在使用 String.CompareTo() 来比较字符串。
  2. String.CompareTo()- 有特殊的行为,它将其视为连字符而不是减号。 (注意:此连字符不应与字符代码为 U00AD 的软连字符混淆。)

考虑这段代码:

Console.WriteLine("-1".CompareTo("0")); // 1
Console.WriteLine("-1".CompareTo("1")); // 1
Console.WriteLine("-1".CompareTo("2")); // -1

请注意,与直觉相反,“-1”是如何在“0”和“1”之后但在“2”之前的。

这解释了为什么在对字符串进行排序时,“-1”既不是最大值也不是最小值。

Also see the answer to this question for more details.