6

I have a list which I need to order eg.

var list = someelements;

I also have a parameter which says by which property and what direction I should order list data eg.

var sortby = "Name";
var sortdirection = "desc";

I was wondering if I can match string property name with the right property so I get:

var list = someelements.OrderBy(x => x.Name).ToList();

when sortby == "Name" without the need of using switch loop to check property name and assign a correct property to OrderBy.

Same I would like to achieve with select either OrderBy or OrderByDescending depending whether I get sortdirection = "asc" or sortdirection = "desc"

Is it possible and if yes, how?

double-beep
  • 3,889
  • 12
  • 24
  • 35
nickornotto
  • 1,466
  • 2
  • 29
  • 55
  • Relying on `OrderBy` or on `OrderByDescending` on acount of the `sortDirection` values is quite straightforward: use a condition (even a ternary operator would do the job in this situation). – varocarbas Nov 30 '15 at 16:16
  • Possible duplicate of [How can I do an OrderBy with a dynamic string parameter?](https://stackoverflow.com/questions/2728340/how-can-i-do-an-orderby-with-a-dynamic-string-parameter) – mkimmet Sep 07 '17 at 20:20

2 Answers2

6

You can get Dynamic Linq through Nuget. Then you can use .OrderBy(sortby + " " + sortdirection). Here is the link: Dynamic Linq.

Aleksa
  • 2,608
  • 3
  • 26
  • 39
  • Thanks for the answer, I used the port of this library for .net core: https://www.nuget.org/packages/System.Linq.Dynamic.Core – MIP1983 Oct 11 '17 at 13:54
4

Here is one solution that does not use Dynamic Linq:

public class Helper
{
    public static IEnumerable<T> OrderByDynamic<T>(IEnumerable<T> items, string sortby, string sort_direction)
    {
        var property = typeof (T).GetProperty(sortby);

        var result = typeof(Helper)
            .GetMethod("OrderByDynamic_Private", BindingFlags.NonPublic | BindingFlags.Static)
            .MakeGenericMethod(typeof (T), property.PropertyType)
            .Invoke(null, new object[]{ items, sortby, sort_direction});

        return (IEnumerable<T>)result;
    }

    private static IEnumerable<T> OrderByDynamic_Private<T,TKey>(IEnumerable<T> items, string sortby, string sort_direction)
    {
        var parameter = Expression.Parameter(typeof (T), "x");

        Expression<Func<T, TKey>> property_access_expression =
            Expression.Lambda<Func<T, TKey>>(
                Expression.Property(parameter, sortby),
                parameter);

        if (sort_direction == "asc")
        {
            return items.OrderBy(property_access_expression.Compile());
        }

        if (sort_direction == "desc")
        {
            return items.OrderByDescending(property_access_expression.Compile());
        }

        throw new Exception("Invalid Sort Direction");
    }
}

You can use it like this:

var result = Helper.OrderByDynamic(list, "Name", "desc").ToList();
Yacoub Massad
  • 26,006
  • 2
  • 31
  • 56