Linq / lambda expressions

Tries something with Linq / Lambda but has no idea where to look.

I am working on a simple sort in ASP.NET GridView. Here's some sample code:

IQueryable<User> query = (from c in users select c).AsQueryable<User>();

if (isAscending)
{
    switch (e.SortExpression)
    {
        case "Name":
            query.OrderBy(c => c.Name);
            break;
        default:
            break;
    }
}
else
{
    switch (e.SortExpression)
    {
        case "Name":
            query.OrderByDescending(c => c.Name);
            break;
         default:
             break;
    }
}

grid.DataSource = query.ToList();
grid.DataBind();

      

I am however not satisfied with the code as it is very error sensitive and requires a lot of duplicate code. I am hoping to solve this using Lambda expressions, but I have no idea how. This is where I would like to go:

IQueryable<User> query = (from c in users select c).AsQueryable<User>();

var param = null;

switch (e.SortExpression)
{
    case "Name":
        param = (c => c.Name);
        break;
    default:
        break;
}

if (isAscending)
{
    query.OrderBy(param);
}
else
{
    query.OrderByDescending(param);
}

grid.DataSource = query.ToList();
grid.DataBind();

      

Can anyone help me? Thank!

+2


source to share


1 answer


At the moment your code is broken - you are calling OrderBy / OrderByDescending but not using the result. You need

query = query.OrderBy(param);

      

and etc.

As far as conditional ordering is concerned, the problem is that you cannot declare a type param

, because the type of the ordering key can change depending on the sorting expression.

As a workaround, you can write your own extension method:



public static IOrderedQueryable<TSource> OrderByWithDirection<TSource, TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool ascending)
{
    return ascending ? source.OrderBy(keySelector) 
                     : source.OrderByDescending(keySelector);
}

      

Then your code will look like this:

IQueryable<User> query = (from c in users select c).AsQueryable<User>();

switch (e.SortExpression)
{
    case "Name":
        query = query.OrderByWithDirection(c => c.Name, isAscending);
        break;
    // etc
    default:
        break;
}

      

(Why are you calling AsQueryable

, by the way?)

+4


source







All Articles