在C#中排序一个列表

时间:2011-05-17 14:09:44

标签: c# list

我有一个Employee对象列表.Employee Class可以如下:

Class Emplyoyee
{
    public string name;
    public string DateOFJoining; //Please note here date is in string format
}

现在我想显示最新员工的员工名单,以便使用以下代码:

List<Employee> lst = GetEmployes();          
lst = lst.OrderByDescending(x => x.DateOFJoining).ToList();

//Here binding to the repeater
rptEmp.DataSource = lst.Take(2);
rptEmp.DataBind();

问题:这里的订购处理日期为字符串。但我想按日期订购。任何人都可以帮我这个吗?

提前致谢。

2 个答案:

答案 0 :(得分:7)

您需要将x.DateOfJoining转换为DateTime表达式中的OrderByDescending。如果您对日期的质量有信心,可以尝试:

lst = lst.OrderByDescending(x => DateTime.Parse(x.DateOfJoining)).ToList();

答案 1 :(得分:3)

您可以Employee实施System.IComparable界面。然后只需使用List.Sort()方法为员工订购。

例如:

Class Employee : IComparable
{
    public string name;
    public string DateOFJoining; //Please note here date is in string format

    public int CompareTo(object obj) {
        if(obj is Employee) {
            Employee= (Employee) obj;

            return Convert.ToDateTime(DateOfJoining).CompareTo(Convert.ToDateTime(e.DateOfJoining));
        }

        throw new ArgumentException("object is not an Employee");    
    }
}