Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Linq & ICompare

I'm trying to make use of James McCormack's guide to using a custom IComparer with Dynamic Linq. - see http://zootfroot.blogspot.co.uk/2009/10/dynamic-linq-orderby.html?showComment=1347276236930#c11348033278810583

I use a query to pull back an Enumerable of string values:

.Select("fieldname").Distinct()

Then try to use

.OrderBy(item=>item.GetReflectedPropertyValue("fieldname"),new myComparer()) 

GetReflectedPropertyValue is a helper method defined by James as

public static string GetReflectedPropertyValue(this object subject, string field)
{
object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
return reflectedValue != null ? reflectedValue.ToString() : "";
}

But get the error "'System.Collections.Generic.IEnumerable' does not contain a definition for 'OrderBy' and the best extension method overload 'System.Linq.Dynamic.DynamicQueryable.OrderBy(System.Linq.IQueryable, string, params object[])' has some invalid arguments"

Any ideas? I'm new to this and just trying to get something working before I get the time to actually go through and learn it properly.

like image 335
John Griffiths Avatar asked Dec 19 '25 15:12

John Griffiths


1 Answers

it's hard to tell based only on what you've posted because the resolution of OrderBy will depend on the implementation of myConverter. But, Since GetReflectedPropertyValue returns string, myConverter must implement IConverter<String> to be used with OrderBy. If it doesn't, and it implements something like IComparer<MyItem> then compiler is really looking for a method OrderBy(this IEnumerable<object>, Func<object,string>, IComparer<MyItem>) which doesn't exist and spits out that error.

If that isn't clear, provide the details of myConverter and I can be more specific.

If you're using something that doesn't implement IComparer<T>, then you can wrap the IComparer with something that implements IComparable<string> so that it is compatible with Orderby. For example:

public class MyStringComparer : IComparer<String>
{
    readonly IComparer comparer = new MyComparer();
    public int Compare(string x, string y)
    {
        return comparer.Compare(x, y);
    }
}
like image 67
Peter Ritchie Avatar answered Dec 21 '25 04:12

Peter Ritchie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!