我正在尝试对ListView
进行排序,该DateTime
也有public bool isDate(Object obj)
{
string strDate = obj.ToString();
try
{
DateTime dt = DateTime.Parse(strDate);
if (dt != DateTime.MinValue && dt != DateTime.MaxValue)
return true;
return false;
}
catch
{
return false;
}
}
public int Compare(object o1, object o2)
{
if (!(o1 is ListViewItem))
return (0);
if (!(o2 is ListViewItem))
return (0);
ListViewItem lvi1 = (ListViewItem)o2;
string str1 = lvi1.SubItems[ByColumn].Text;
ListViewItem lvi2 = (ListViewItem)o1;
string str2 = lvi2.SubItems[ByColumn].Text;
int result;
if (lvi1.ListView.Sorting == SortOrder.Ascending)
{
if (isDate(str1) && isDate(str2))
result = DateTime.Compare(DateTime.Parse(str1), DateTime.Parse(str2));
else
result = String.Compare(str1, str2);
}
else
result = String.Compare(str2, str1);
LastSort = ByColumn;
return result;
}
列。这是我使用的代码:
ListView
public int Compare(object o1, object o2)
{
var lvi1 = o2 as ListViewItem;
var lvi2 = o1 as ListViewItem;
if (lvi1 == null || lvi2 == null)
return 0;
string str1 = lvi1.SubItems[ByColumn].Text;
string str2 = lvi2.SubItems[ByColumn].Text;
int result;
DateTime dateValue1 = new DateTime();
DateTime dateValue2 = new DateTime();
if (lvi1.ListView.Sorting == SortOrder.Ascending)
{
if (DateTime.TryParse(str1, out dateValue1) && DateTime.TryParse(str2, out dateValue2))
result = DateTime.Compare(dateValue1, dateValue2);
else
result = String.Compare(str1, str2);
}
else
{
if (DateTime.TryParse(str1, out dateValue1) && DateTime.TryParse(str2, out dateValue2))
result = DateTime.Compare(dateValue2, dateValue1);
else
result = String.Compare(str2, str1);
}
LastSort = ByColumn;
return result;
}
包含大约2000个条目,问题在于它非常慢。我究竟做错了什么?有什么想法吗?
提前致谢!
编辑:非常感谢。我是新手,现在是我的代码。它更快,我修正了我的逻辑。
{{1}}
答案 0 :(得分:1)
我想到了一些优化:
DateTime.TryParse
而不是两次投射:
if (!(o1 is ListViewItem)) return (0);
ListViewItem lvi1 = (ListViewItem)o2;
使用一次投射:
var lvi1 = o2 as ListViewItem;
if (lvi1 == null)
return 0;
另外,我建议检查您的代码逻辑(正如我在评论中提到的那样)。
答案 1 :(得分:1)
你不能只将ListViewItem.Tag设置为DateTime吗?然后在比较DateTimes时:
DateTime d = (DateTime)ListViewItem.Tag;