Vicky
Vicky

Reputation:

Binding to ASP.NET GridView

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?

Upvotes: 0

Views: 299

Answers (2)

mirezus
mirezus

Reputation: 14246

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

Upvotes: 2

Henk
Henk

Reputation: 704

        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();

Upvotes: 2

Related Questions