如何基于列表项对数组列表进行排序

本文关键字:列表 数组 排序 何基于 | 更新日期: 2023-09-27 18:09:25

我有一个数组列表,其中包含列表项日期和一些字符串。我想在日期的基础上对数组列表进行排序。我有以下伪代码为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';

所以最后我的数组列表包含下面的数据
文本 值
11-04-2013 -允许120-M
5-01-2013 -允许101-M
2-02-2013 -允许121-M
8-8-2012 -不允许

我想按日期升序排序这个数组列表。

如何基于列表项对数组列表进行排序

定义自定义比较器:

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);

如果您定义一个具有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;
     //}
 }