views:

37

answers:

1

I want to pass the sort field and direction dynamically to the LINQ to SQL codes. But I could not find the way to perform like that because if I could not write users.OrderBy(d => Field);

Is there any way to pass the dynamic field to sort? Thanks.

private static IQueryable<user> GetUserData(String Field, String Direction)
{
    UserDataContext dc = new UserDataContext();

    var users = from d
                    in dc.users
                orderby Field ascending
                select d;

    if (Direction == "ascending")
    {
        return users.OrderBy(d => d.userName);
    }
    else
    {
        return users.OrderByDescending(d => d.userName);
    }
}
+1  A: 

The Queryable.OrderBy extension method takes a parameter of type Expression<Func<TSource, TKey>>. This does not have to be created using a lambda expression, but can be constructed by hand via the Expression class, which lets you construct any kind of expression dynamically in code. This can be used to create a dynamic OrderBy method.

I also read about the LINQ Dynamic Query Library in a recent question, which seems to have a method that does exactly that. It's apparently included as a code example in some sample collection for VS2008, read the link for more information.

Matti Virkkunen