我有以下代码:
var emp = new List<Employee>
{
new Employee{ID=1, EmpFname="matt", EmpLName="Cook"},
new Employee{ID=2, EmpFname="mary", EmpLname="John"}
};
如何通过EmpLName对emp进行排序并将其绑定到GridView?如何指定asc或desc?
答案 0 :(得分:2)
List<Employee> temp = new List<Employee> {
new Employee { ID = 1, EmpFname = "matt", EmpLName = "Cook" },
new Employee { ID = 2, EmpFname = "mary", EmpLName = "John" } };
temp.Sort(delegate(Employee e1, Employee e2)
{
// returns asc
return e1.EmpLName.CompareTo(e2.EmpLName);
// returns desc
// return e2.EmpLName.CompareTo(e1.EmpLName);
});
// no need to use var keyword, just bind the List
MyGridView.DataSource = temp;
MyGridView.DataBind();
答案 1 :(得分:2)
使用LINQ的简单方法:
var sortedEmpList = ( from e in emp
orderby e.EmpLName
select e).ToList()
);
您还可以通过在 orderby 之后添加更多属性来继续按其他属性进行排序。
orderby e.EmpLName, e.EmpFName //, ...
如果您需要,请选择降序
orderby e.EmpLName descending