locked
LINQ to Objects Using Expression Tree AND Custom IComparer<T> RRS feed

  • Question

  • I'm having issues with getting a LINQ OrderBy extension method call to work with both a simple lambda expression tree and a custom IComparer<T>.  I know I am probably missing something simple, and was hoping someone could point me in the right direction.  Below is the applicable code: 

    public static Expression<Func<T, object>> GetPropertyLambda(string propertyName)
    {
     ParameterExpression expression = Expression.Parameter(typeof (T), "item");
     Expression member = Expression.Property(expression, propertyName);
     if (member.Type.IsValueType)
     {
     member = Expression.Convert(member, typeof (object));
     }
     return Expression.Lambda<Func<T, object>>(member, expression);
    }
    
    var sortExpression =
     ExpressionTreeHelper<GroupExclusionItem>.GetPropertyLambda("propertyName");
    
    sortedExclusionItems =
     groupExclusionItems.OrderBy(sortExpression.Compile(), new NaturalSortComparer<string>()).ToList();
    

    The OrderBy with the sort expression works without the IComparer<T>, but I don't like the default sort order.  It also works with the custom comparer when I specify a traditional lambda expression with a specific property name.  I'm pretty sure i'm passing the right argument types - Func<TSource,TKey> (which is what sortExpression.Compile() outputs) and IComparer<T>.  When trying to compile, I get the following error:

    "The type arguments for method 'System.Linq.Enumerable.OrderBy<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>, System.Collections.Generic.IComparer<TKey>)' cannot be inferred from the usage. Try specifying the type arguments explicitly."

     

    I know I'm probably missing something small, and was hoping someone would be able to point me to it.  Any help would be appreciated.  Thanks.

     

     

     

    Dale

     

    Wednesday, October 13, 2010 7:02 PM

Answers

  • Hi,

    If you are trying to compare string type, sortExpression.Compile() has to return Func<T,string>. But in your case the returned predicate is Func<T,object>. 

    Regards,

    Nyi Nyi


    Happy programming .net
    • Marked as answer by liurong luo Wednesday, October 20, 2010 10:59 AM
    Thursday, October 14, 2010 2:37 PM

All replies

  • Hi,

    If you are trying to compare string type, sortExpression.Compile() has to return Func<T,string>. But in your case the returned predicate is Func<T,object>. 

    Regards,

    Nyi Nyi


    Happy programming .net
    • Marked as answer by liurong luo Wednesday, October 20, 2010 10:59 AM
    Thursday, October 14, 2010 2:37 PM
  • Like I said, Nyi Nyi, I knew I overlooked something small.  I'm still new to this type inference thing.  Thanks for the pointer.

    Dale

    • Proposed as answer by Crazy T-Mack Monday, January 24, 2011 8:05 PM
    Thursday, October 14, 2010 3:47 PM