在控件ObjectListView(http://objectlistview.sourceforge.net/html/cookbook.htm)中,我正在尝试添加自定义排序器,忽略“The”和“A”前缀。
我设法使用常规ListView,但现在我切换到ObjectListView(更多功能和轻松),我似乎无法做同样的事情。
以下是我认为的ObjectListView代码中的主比较器......
public int Compare(object x, object y)
{
return this.Compare((OLVListItem)x, (OLVListItem)y);
}
升序的原始分拣机,例如(忽略“A”和“The”)
public class CustomSortAsc : IComparer
{
int IComparer.Compare(Object x, Object y)
{
string[] px = Convert.ToString(x).Split(' ');
string[] py = Convert.ToString(y).Split(' ');
string newX = "";
string newY = "";
for (int i = 0; i < px.Length; i++)
{
px[i] = px[i].Replace("{", "");
px[i] = px[i].Replace("}", "");
}
for (int i = 0; i < py.Length; i++)
{
py[i] = py[i].Replace("{", "");
py[i] = py[i].Replace("}", "");
}
if ((px[1].ToLower() == "a") || (px[1].ToLower() == "the"))
{
if (px.Length > 1)
{
for (int i = 2; i < px.Length; i++)
newX += px[i];
}
}
else
{
for (int i = 1; i < px.Length; i++)
newX += px[i];
}
if ((py[1].ToLower() == "a") || (py[1].ToLower() == "the"))
{
if (py.Length > 1)
{
for (int i = 2; i < py.Length; i++)
newY += py[i];
}
}
else
{
for (int i = 1; i < py.Length; i++)
newY += py[i];
}
return ((new CaseInsensitiveComparer()).Compare(newX, newY));
}
答案 0 :(得分:2)
虽然它与您的问题没有任何直接关系,但我可以建议一些代码改进吗?显然你的原始x和y对象是空格分隔的单词。不确定你是否故意不将它们与空间重新加入,但我保持这样。
public static class Extensions
{
public static IEnumerable<T> SkipIf<T>(this IEnumerable<T> items, Predicate<T> pred)
{
return pred(items.First()) ? items.Skip(1) : items;
}
}
public class CustomSortAsc : IComparer
{
int IComparer.Compare(Object x, Object y)
{
var ignorePredicates = new List<string> { "a", "the" };
var px = Convert
.ToString(x)
.Replace("{", "")
.Replace("}", "")
.Split(' ')
.SkipIf(s => ignorePredicates.Contains(s.ToLower()))
.ToArray();
var py = Convert
.ToString(y)
.Replace("{", "")
.Replace("}", "")
.Split(' ')
.SkipIf(s => ignorePredicates.Contains(s.ToLower()))
.ToArray();
var newX = string.Join("", px);
var newY = string.Join("", py);
return string.Compare(newX, newY, true);
}
}
您可以使用SkipWhile<>
,但这会在开头跳过多个“a”和“the”。可能没问题 - 那么你不需要SkipIf<>
扩展名。
答案 1 :(得分:1)
安装CustomSorter委托,并在该委托中将ListItemSorter放到ObjectListView
this.incidentListView.CustomSorter = delegate(OLVColumn column, SortOrder order) {
this.incidentListView.ListViewItemSorter = new CustomSortAsc();
};
比在每次比较中完成所有这些工作更好,在每个模型对象上缓存排序值。如果值为“{The} Nine Nine Yards”,则存储“整个九码”并对这些值进行简单(快速)字符串比较。
ObjectListView确实有own forum。