tags:

views:

242

answers:

6

Hello,

I am sorting a GridView bind to a ananymous type.

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    List<object> lb = (List<object>)ReturnAnony(); // Not working
    // ?? What to write here
}

object ReturnAnony()
{
    var anony = // I create the ananymous type and return    
    return anony;
}
A: 

Not really sure what you want.

If you are going to create a List that is typed to anonymous type, you can use a currying function to help you:

public List<T> makeAList<T>(T x)
{
    var l = new List<T>();

    l.Add(x);
    return l;
}

Is that what you want?

Otherwise, you cannot reference the anonymous type outside of its scope unless you create a path to bridge the type information over to your code... which... in the end you should just made a new class.

chakrit
+1  A: 

What do you want to do with lb?

Generally speaking, anonymous types aren't really suitable to be returned from methods, because you can't express the return type.

Have you considered expanding your anonymous type into a normal, named type?

Jon Skeet
A: 

If you want to access your data item in a GrideView EventHandler you really shouldn't use an anonymous type. Anonymous types are only available within the method scope they are defined within so it's only known as object by the time you get to another scope. To then access the properties you'll need to use refection.

But for doing sorting you can have it a bit crazily dynamic, see the response I did in this question: http://stackoverflow.com/questions/307512/how-do-i-apply-orderby-on-an-iqueryable-using-a-string-column-name-within-a-gener#307600

It looks how to do an OrderBy statement dynamically, but you could apply the principles to any kind of LINQ filter.

Slace
A: 

If you are sorting an ASP.NET GridView you can simply specify the field to sort as a string in the SortExpression property of the event args object.

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    e.SortExpression = "FieldABC";
}

object ReturnAnony()
{
    var anony = new object { FieldABC = 123 };
    return anony;
}

This should allow you to sort on any fields of the anonymous type.

You don't need to create any list.

chakrit
A: 

Hi.. Thanks everyone for their answer.

If I have a List with an array of Employee objects in it, how do i sort it via EmployeeFirstName?

A: 

Regarding your other question, here's how:

var l = new List<Employee>();

l.Sort((x, y) => (x.FirstName.CompareTo(y.FirstName)));

Please edit the question in or just ask another question.

chakrit