Reputation: 33
I'm trying to use IComparer with a generic type.
The code below generates the following error: "The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly."
If I remove the custom comparer from the OrderBy call then the code compiles and orders fine, however I need to be able to pass in my icomparer. Also worth noting is that the code below works if i use type of object/string etc. but fails when I try and use generic type
public IQueryable<T> OrderResults<T, TU>(IQueryable<T> queryData, IComparer<TU> customComparer, string sortColumnName)
{
var sortPropertyInfo = queryData.First().GetType().GetProperty(sortColumnName);
return queryData.OrderBy(x => sortPropertyInfo.GetValue(x, null), customComparer);
}
Upvotes: 3
Views: 394
Reputation: 2797
Your snippet has some ambiguity caused by the fact that GetValue(x,null)
returns type System.Object
. Try the following:
public IQueryable<T> OrderResults<T, TU>(IQueryable<T> queryData, IComparer<TU> customComparer, string sortColumnName)
{
var sortPropertyInfo = queryData.First().GetType().GetProperty(sortColumnName);
return queryData.OrderBy(x => (TU)sortPropertyInfo.GetValue(x, null), customComparer);
}
This at least doesn't have a compile time error. If you have some code you're using for testing, I can verify that it works....
Upvotes: 2