2012-09-10 43 views
3

我試圖利用詹姆斯麥考馬克的指南來使用動態Linq自定義IComparer。 - 看到http://zootfroot.blogspot.co.uk/2009/10/dynamic-linq-orderby.html?showComment=1347276236930#c11348033278810583動態Linq&ICompare

我使用查詢拉字符串值回可枚舉:

.Select("fieldname").Distinct() 

然後嘗試使用

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

GetReflectedPropertyValue是詹姆斯定義一個輔助方法

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

但是得到錯誤「'System.Collections.Generic.IEnumerable'd oes不包含'OrderBy'和最好的擴展方法重載定義'System.Linq.Dynamic.DynamicQueryable.OrderBy(System.Linq.IQueryable,string,params object [])'有一些無效參數「

任何想法?我是新來的,只是在我花時間實際完成並正確地學習之前嘗試做一些工作。

回答

2

根據您發佈的內容很難分辨,因爲OrderBy的分辨率取決於myConverter的實施。但是,由於GetReflectedPropertyValue返回string,myConverter必須實現IConverter<String>以與OrderBy一起使用。如果沒有,並且它實現了類似IComparer<MyItem>的東西,那麼編譯器真的在尋找一種不存在的方法OrderBy(this IEnumerable<object>, Func<object,string>, IComparer<MyItem>),並吐出該錯誤。

如果不清楚,請提供myConverter的詳細信息,我可以更具體。

如果您使用的東西,不執行IComparer<T>,那麼你就可以用的東西,實現IComparable<string>使其與Orderby兼容包裹IComparer。例如:

public class MyStringComparer : IComparer<String> 
{ 
    readonly IComparer comparer = new MyComparer(); 
    public int Compare(string x, string y) 
    { 
     return comparer.Compare(x, y); 
    } 
} 
+0

感謝您的回覆。我實際上使用這個比較器http://www.davekoelle.com/files/AlphanumComparator.cs,我認爲它是好的,因爲它期待一個普通的對象? –

+0

順便說一句,當我嘗試你的包裝,我得到這個消息「的非泛型類型'System.Collections.IComparer'不能用於類型參數」 - 忽略這一點,意識到我沒有包括System.Collections.Generic –

+0

是的,你需要正確的使用指令:) –