我有arraylist,其中包含包含日期和一些字符串的listitem。我想在Date的基础上对这个Arraylist进行排序。 我有关于arraylist项目的伪代码。
ArrayList _arListDAte = new ArrayList();
//foreach loop for DAtatable rows
ListItem lstitem = new ListItem();
//here is condition for assigning text to lstitem
//if condition match
lstitem.Text = Today.Date() + ' - Allowed'
//else
lstitem.Text = Today.Date() + ' - Not allowed'
listitem.value = datarow[id]+'-M';
所以最后我的Arraylist包含以下数据
文字VAlue
11-04-2013 - 允许120-M
5-01-2013 - 允许101-M
2-02-2013 - 允许121-M
8-8-2012 - 不允许126-NM
我想按日期按升序排序这个arraylist。
答案 0 :(得分:1)
定义自定义比较器:
public class DateComparer: IComparer {
int IComparer.Compare( Object x, Object y ) {
String a = (x as ListItem).Text;
String b = (y as ListItem).Text;
DateTime aDate = DateTime.Parse(a.split(null)[0]);
DateTime bDate = DateTime.Parse(b.split(null)[0]);
return DateTime.Compare(aDate, bDate);
}
}
在你的代码之后调用它:
IComparer comp = new DateComparer();
arListDAte.Sort(comp);
答案 1 :(得分:0)
如果您定义一个具有DateTime成员而不是使用ListItem类的自定义类,则会变得更简单。这可以避免在处理保存为字符串的DateTime值时出现任何与文化相关的问题。
static void Main()
{
ArrayList _arListDAte = new ArrayList();
CustomListItem listItem = new CustomListItem();
bool condition = true;
DateTime date = new DateTime(2013, 04, 15);
if(condition)
{
listItem.Text = date + " - Allowed";
listItem.Date = date;
}
else
{
listItem.Text = date + " - Allowed";
listItem.Date = date;
}
_arListDAte.Add(listItem);
listItem = new CustomListItem();
date = new DateTime(2013, 04, 13);
if (condition)
{
listItem.Text = date + " - Allowed";
listItem.Date = date;
}
else
{
listItem.Text = date + " - Allowed";
listItem.Date = date;
}
_arListDAte.Add(listItem);
listItem = new CustomListItem();
date = new DateTime(2013, 04, 18);
if (condition)
{
listItem.Text = date + " - Allowed";
listItem.Date = date;
}
else
{
listItem.Text = date + " - Allowed";
listItem.Date = date;
}
_arListDAte.Add(listItem);
_arListDAte.Sort();
}
public class CustomListItem : IComparable
{
public string Text { get; set; }
public string Value { get; set; }
public DateTime Date { get; set; }
//Sort Ascending Order
public int CompareTo(object obj)
{
CustomListItem customListItem = obj as CustomListItem;
if (customListItem != null)
return this.Date.CompareTo(customListItem.Date);
return 0;
}
// Uncomment for descending sort
//public int CompareTo(object obj)
//{
// CustomListItem customListItem = obj as CustomListItem;
// if (customListItem != null)
// return customListItem.Date.CompareTo(this.Date);
// return 0;
//}
}