问题
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.
回答1:
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);
}
}
来源:https://stackoverflow.com/questions/12350965/dynamic-linq-icompare