Custom IComparer in LINQ OrderBy Lambda expression

I have a custom comparer I want to use with OrderBy. I am trying to build a LINQ expression to make it work. So in essence, I am trying to put together an IComparer, OrderBy inLinq expression.

The expression I am trying to build should look something like:

source => source.OrderBy(lambdaParameter => lambdaParameter.Name, new Parsers.NumericComparer()). 

With the code below the expression

'{source => source.OrderBy(lambdaParameter => lambdaParameter.Name)}' 

is built and I am trying to add this custom Icomparable to this expression

new Parsers.NumericComparer(). 

This is because I need to do a natural sort. Can someone please help me on how to include this expression. I am trying to read several threads for the past few hours but I have not done understood LINQ expressions well enough yet to implement this. Thanks!

private void CreateOrderByMethod(PropertyDescriptor prop, string orderByMethodName, string cacheKey)
     Create a generic method implementation for IEnumerable<T>.
     Cache it.
    var sourceParameter = Expression.Parameter(typeof(List<T>), "source");
    var lambdaParameter = Expression.Parameter(typeof(T), "lambdaParameter");

    var accesedMember = typeof(T).GetProperty(prop.Name);
    var propertySelectorLambda =
        Expression.Lambda(Expression.MakeMemberAccess(lambdaParameter, accesedMember), lambdaParameter);

    var orderByMethod = typeof(Enumerable).GetMethods()
                                  .Where(a => a.Name == orderByMethodName &&
                                               a.GetParameters().Length == 2)
                                  .MakeGenericMethod(typeof(T), prop.PropertyType);
    var orderByExpression = Expression.Lambda<Func<List<T>, IEnumerable<T>>>(
                                        new Expression[] { sourceParameter, 
                                                       propertySelectorLambda }),
    cachedOrderByExpressions.Add(cacheKey, orderByExpression.Compile());


To create an expression that creates a new instance of an object, use Expression.New.

var newParser = Expression.New(typeof(Parsers.NumericComparer));

Then I suggest you use this overload of Expression.Call instead, so that you don't have to go and manually grab the MethodInfo:

var orderByCall = Expression.Call(
    new [] { typeof(T), prop.PropertyType },
    sourceParameter, propertySelectorLambda, newParser);

Need Your Help

How do I get an APP ID for Facebook on my web site?

login web facebook-social-plugins facebook-login

First of all, my simple purpose is to add a Facebook login button to my web site. So I go to the login button description.

how to fit the video inside of an iframe?

javascript html css video iframe

I am using an iframe tag to play a video, I extended the iframe full width and height of the parent div, like this :