I have a list of Employee objects .Employee Class can be as below:
Class Emplyoyee
{
开发者_如何学Go public string name;
public string DateOFJoining; //Please note here date is in string format
}
Now i want to display the list of employee with latest employee on top so am using below code for it :
List<Employee> lst = GetEmployes();
lst = lst.OrderByDescending(x => x.DateOFJoining).ToList();
//Here binding to the repeater
rptEmp.DataSource = lst.Take(2);
rptEmp.DataBind();
Problem: Here its ordering treating date as string .But i want to order by date.Can anyone help me on this?
Thanks in advance.
You would need to convert x.DateOfJoining
into a DateTime
in the OrderByDescending
expression. If you're confident in the quality of your dates, you could try:
lst = lst.OrderByDescending(x => DateTime.Parse(x.DateOfJoining)).ToList();
You can have Employee
implement the System.IComparable
interface. and then just use the List.Sort()
method to order the employees.
for example:
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");
}
}
精彩评论