views:

155

answers:

2

I have the following code:

var emp = new List<Employee>
{    
   new Employee{ID=1, EmpFname="matt", EmpLName="Cook"},  
   new Employee{ID=2, EmpFname="mary", EmpLname="John"}
};

How do I sort emp by EmpLName and bind it to a GridView? How do I specify asc or desc?

+2  A: 
        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();
Henk
+1 This is what i do too. Your Employee needs a Sort() delegate method. You can do this where you define your Employee class too. Call Sort() on your List<Employee> then bind it.
Dave
+1  A: 

Simple way with LINQ:

var sortedEmpList = ( from e in emp
orderby e.EmpLName
select e).ToList()
);

you can also keep sorting by the other properties, by adding more of them after the orderby.

orderby e.EmpLName, e.EmpFName  //, ...

Then choose descending if you want that...

orderby e.EmpLName descending
mirezus