如何让我的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时间(R) - XX - XX
-6 DAG(E)-18时间(R) - XX - XX
8 DAG(E)1周时间(R) - XX - XX
8 DAG(E)4时间(R) - XX - XX
预期输出是:
- 6 DAG(E)-18时间(R) - XX - XX
-4 DAG(E)-17时间(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++;
}
}
这是有点不清楚;输出如何与程序片断相关并不明显。请修改。 – Bathsheba
您能否提供预期的行为和实际的行为?例如。预期的“-1”>“-5”,实际的“-1”<“-5” –
而且,给我们真实的输入值。你在比较“-4”和“-17”还是“-4 dag(e)”和“-17 time(r)”? – Pikoh