如何让我的Comparer考虑负数? 知道它对我的字符串中的数字进行排序,但它省略了减号(“减法”)符号。所以我得到了错误的输出,见下面的代码。
public class MixedNumbersAndStringsComparer : IComparer<string>
{
public int Compare(string x, string y)
{
double xVal, yVal;
if (double.TryParse(x, out xVal) && double.TryParse(y, out yVal))
return xVal.CompareTo(yVal);
else
return string.Compare(x, y);
}
}
实际输出:
0 dag(e)5次(r) - xx - xx
3 dag(e)3次(r) - xx - xx
-4 dag(e)-17 time(r) - xx - xx
-6 dag(e)-18 time(r) - xx - xx
8 dag(e)1次(r) - xx - xx
8 dag(e)4次(r) - xx - xx
预期输出为:
-6 dag(e)-18 time(r) - xx - xx
-4 dag(e)-17 time(r) - xx - xx
0 dag(e)5次(r) - xx - xx
3 dag(e)3次(r) - xx - xx
8 dag(e)1次(r) - xx - xx
8 dag(e)4次(r) - xx - xx
输入数据是:
TimeSpan tidtilbage = timeToExpire.GetTimeRemainingUntilPasswordExpiration("DOMAIN", p.SamAccountName);
TimeSpan under10 = new TimeSpan(10, 00, 00, 00);
TimeSpan ikkeMinus10 = new TimeSpan(-10, 00, 00, 00);
if (tidtilbage < under10 && tidtilbage > ikkeMinus10)
{
if (u.Enabled == true)
{
string lines = tidtilbage.Days + " dag(e) "
+ tidtilbage.Hours + " time(r)" + " - "
+ p.SamAccountName.ToUpper() + " - " + p.DisplayName + "\n\n";
sorted[i] = lines;
Array.Sort(sorted, new MixedNumbersAndStringsComparer());
i++;
}
}
答案 0 :(得分:3)
您似乎正在寻找逻辑排序(即将字符串中的整数视为整数:"10"
&gt ; "9"
当您按逻辑排序时,"10"
&lt; "9"
当您按字典顺序排序时)。快速而脏( interop )实现:
using System.Runtime.InteropServices;
...
public sealed class MixedNumbersAndStringsComparer : IComparer<string> {
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string left, string right);
public int Compare(string left, string right) {
return StrCmpLogicalW(left, right);
}
}
你甚至可以摆脱IComparer<string>
:
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string left, string right);
...
string[] data = ...;
Array.Sort(data, (left, right) => StrCmpLogicalW(left, right));
答案 1 :(得分:1)
如果需要,SafeNativeMethods是您必须实现的类。 在本课程中,您必须添加以下代码:
[DllImport("shlwapi.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
static extern int StrCmpLogicalW(string x, string y);
然而,在Dmitry的回答中,DllImport已经在同一个类中实现了。因此,您不必撰写&#34; SafeNativeMethods&#34;。
德米特里的正确代码是:
using System.Runtime.InteropServices;
...
public sealed class MixedNumbersAndStringsComparer : IComparer<string> {
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string left, string right);
public int Compare(string left, string right) {
return MixedNumbersAndStringsComparer.StrCmpLogicalW(left, right); // or return StrCmpLogicalW(left, right);
}
}
您好。