【发布时间】:2016-07-03 16:26:52
【问题描述】:
我有一个包含"Others" 的字符串列表。我得到这个下拉列表。我按字母顺序对这个列表进行排序。但我需要"Others" 总是在列表的末尾。我不想在排序后添加这个元素,这是一种解决方案。有没有其他方法可以通过使用.Sort() 方法的自定义比较器来做同样的事情。我尝试了下面的方法,但没有解决方案。
public class EOComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if (x == null)
{
if (y == null)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == null)
// ...and y is null, x is greater.
{
return 1;
}
else
{
if (x.ToLower().Contains("other"))
{
return -1;
}
else
{
// If the strings are of equal length,
// sort them with ordinary string comparison.
//
return x.CompareTo(y);
}
}
}
}
并将其称为:
EOComparer c = new EOComparer();
a.Sort((x, y) => c.Compare(x.OptionValue, y.OptionValue));
return a;
如果可能,请帮忙。
【问题讨论】:
-
添加“如果 y 包含 'other' return 1” 也
-
为什么不使用字典?将“其他”作为键,将排序列表作为值