2

我有 arraylist,其中 listitem 包含日期和一些字符串。我想根据日期对这个 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 包含以下数据
Text VALue
11-04-2013 - 允许 120-M
5-01-2013 - 允许 101-M
2-02-2013 - 允许 121-M
8-8-2012 - 不允许 126-NM

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

4

2 回答 2

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);
于 2013-04-15T02:31:50.353 回答
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;
     //}
 }
于 2013-04-15T03:00:42.340 回答