13

I'm trying to generate a LINQ OrderBy clause using lambda expressions with an input of the column name of an entity as a string (in the "sortOn" variable below).

The code below works fine for a sortOn value like "Code" generating the lambda

p => p.Code

But I would also like to sort on a child entity, where the lambda might be

p => p.Category.Description

So in this instance, I would just like to set sortOn = "Category.Description" and have the correct lamdba expression generated.

Is this possible? Any suggestions about the best way to do this would be welcomed.

This code works fine for the simple case:

var param = Expression.Parameter(typeof (Product), "p");

var sortExpression = Expression.Lambda<Func<Product, object>>(
    Expression.Property(param, sortOn), param);

if (sortAscending ?? true)
{
   products = products.OrderBy(sortExpression);
}
else
{
   products = products.OrderByDescending(sortExpression);
}

The use-case for this problem is displaying a grid of data and being able to sort the data, simply by passing the column name to be sorted on back to the server. I'd like to make the solution generic, but have started using a particular type (Product in the example) for now.

casperOne
  • 73,706
  • 19
  • 184
  • 253
Appetere
  • 6,003
  • 7
  • 35
  • 46

5 Answers5

21

This will generate proper lambda expression:

var sortOn = "Category.Description";
var param = Expression.Parameter(typeof(Product), "p");
var parts = sortOn.Split('.');

Expression parent = param;

foreach (var part in parts)
{
    parent = Expression.Property(parent, part);
}

var sortExpression = Expression.Lambda<Func<Product, object>>(parent, param);
Tomek
  • 785
  • 4
  • 10
3

Here is an extension OrderBy method which works for any number of nested parameters.

public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string key, bool asc = true)
{
  try
  {
    string orderMethodName = asc ? "OrderBy" : "OrderByDescending";
    Type type = typeof(T);
    Type propertyType = type.GetProperty(key)?.PropertyType; ;

    var param = Expression.Parameter(type, "x");
    Expression parent = param;

    var keyParts = key.Split('.');
    for (int i = 0; i < keyParts.Length; i++)
    {
      var keyPart = keyParts[i];
      parent = Expression.Property(parent, keyPart);

      if (keyParts.Length > 1)
      {
        if (i == 0)
        {
          propertyType = type.GetProperty(keyPart).PropertyType;
        }
        else
        {
          propertyType = propertyType.GetProperty(keyPart).PropertyType;
        }
      }
    }

    MethodCallExpression orderByExpression = Expression.Call(
      typeof(Queryable),
      orderMethodName,
      new Type[] { type, propertyType },
      query.Expression,
      CreateExpression(type, key)
    );

    return query.Provider.CreateQuery<T>(orderByExpression);
  }
  catch (Exception e)
  {
    return query;
  }
}

The CreateExpression method which is used in my solution is defined in this post.

The usage of the OrderBy extension method is as follows.

IQueryable<Foo> q = [Your database context].Foos.AsQueryable();
IQueryable<Foo> p = null;

p = q.OrderBy("myBar.name");  // Ascending sort
// Or
p = q.OrderBy("myBar.name", false);  // Descending sort
// Materialize
var result = p.ToList();

The type Foo and its properties are also taken from the same post as method CreateExpression.

Hope you find this post helpful.

theshinylight
  • 233
  • 4
  • 8
2

You can use the Dynamic LINQ Query Library to do this easily. Assuming you have an IQueryable<T> implementation of Product, you can easily do:

IQueryable<Product> products = ...;

// Order by dynamically.
products = products.OrderBy("Category.Description");

The blog post has a link to the libary, and you'll have to build/include the project in your solution yourself, but it works very well, and the parsing is very robust. It prevents you from having to write the parsing code yourself; even for something so simple, if the requirements expand, the library has you covered, whereas a homegrown solution does not.

It also has a number of other dynamic operators (Select, Where, etc.) so you can perform other dynamic operations.

There's no magic under the hood, it just parses the strings you pass it and then creates the lambda expressions based on the parsing results.

casperOne
  • 73,706
  • 19
  • 184
  • 253
  • Thanks for the suggestion. Would potentially have marked as an answer, but Tomek gave me the approach I wanted. Will definitely look into this as an alternative solution. – Appetere Jul 14 '12 at 19:54
0

If you don't need expressions, how about:

products = products.Orderby(p1 => p1.Code).ThenBy(p2 => p2.Category.Description)
Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
0

Hi you can also create an extension method like which can sort to any depth not only just child

        public static IEnumerable<TSource> CustomOrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        List<string> list=new List<string>();
        List<TSource> returnList=new List<TSource>();
        List<int> indexList = new List<int>();

        if (source == null)
            return null;
        if (source.Count() <= 0)
            return source;
        source.ToList().ForEach(sc=>list.Add(keySelector(sc).ToString())); //Extract the strings of property to be ordered

        list.Sort(); //sort the list of strings

        foreach (string l in list) // extract the list of indexes of source according to the order
        {
            int i=0;
            //list.ForEach(l =>

                foreach (var s in source.ToList())
                {
                    if (keySelector(s).ToString() == l)
                        break;
                    i++;
                }
                indexList.Add(i);
        }
        indexList.ForEach(i=>returnList.Add(source.ElementAt(i))); //rearrange the source according to the above extracted indexes
        return returnList;
    }
}
public class Name
{
    public string FName { get; set; }
    public string LName { get; set; }
}
public class Category
{
    public Name Name { get; set; }
}
public class SortChild
{
    public void SortOn()
    {
        List<Category> category = new List<Category>{new Category(){Name=new Name(){FName="sahil",LName="chauhan"}},
            new Category(){Name=new Name(){FName="pankaj",LName="chauhan"}},
            new Category(){Name=new Name(){FName="harish",LName="thakur"}},
            new Category(){Name=new Name(){FName="deepak",LName="bakseth"}},
            new Category(){Name=new Name(){FName="manish",LName="dhamaka"}},
            new Category(){Name=new Name(){FName="arev",LName="raghaka"}}
        };
        var a = category.CustomOrderBy(s => s.Name.FName);

    }

}

Its custom method and right now it works only for string property only however it can be reactified using generics to work for any primitive type. I hope this will help.

yo chauhan
  • 12,079
  • 4
  • 39
  • 58