views:

419

answers:

1

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"}
   // and so on
};

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

If anyone could explain it using LINQ/Lambda expression, it will be helpful

+1  A: 

You can use OrderBy(Descending) and a lambda expression to select out the name. I'm using "last name, first name" as the key in the example below.

 var ordered = emp.OrderBy( e => e.EmpLName + ", " + e.EmpFName )
                  .ToList();

 var inverse = emp.OrderByDescending(  => e.EmpLName + ", " + e.EmpFName )
                  .ToList();

To bind to the GridView set the DataSource of the GridView to the ordered list. You may be able to skip the ToList step if the GridView takes an IEnumerable as a data source. I don't remember which interfaces are supported off the top of my head.

tvanfosson