我有一個自定義方法獲取與jqGrid一起使用的用於搜索的選擇列表的字符串。jqGrid選擇列表的自定義Linq擴展方法
所需的字符串格式爲":All;value1:text1;value2:text2"
我目前有以下方法可重複使用的方式來實現這一目標:
public static string jqGridFilterSelectList<TSource>(this IQueryable<TSource> source,Expression<Func<TSource, string>> selector)
{
return string.Join(";", source.Select(selector).Distinct().ToArray());
}
該工程確定,但它需要調用是這樣的:
string filterSelectList = service.GetAllUsers().jqGridFilterSelectList(x=>x.User + ":" + x.User);
我不喜歡使用像x=>x.User + ":" + x.User
這樣的選擇器。我想這個轉換成2個重載像這(僞代碼!)
// case where we want the value and text of the select list to be the same
public static string jqGridFilterSelectList<TSource>(this IQueryable<TSource> source,Expression<Func<TSource, string>> selector)
{
return string.Join(";", source.Select(selector + ":" + selector).Distinct().ToArray());
//obviously this won't work, but is it possible in some other way while executing it on the database still? Also is it possible to insist the selector only contains 1 column.
}
//case where we want different text and value
public static string jqGridFilterSelectList<TSource>(this IQueryable<TSource> source,Expression<Func<TSource, string>> textSelector,Expression<Func<TSource, string>> valueSelector)
{
return string.Join(";", source.Select(valueSelector + ":" + textSelector).Distinct().ToArray());
}
我想我大概可以做到這一點使用動態LINQ,但我想知道,如果這是可能的。
這不起作用,當嘗試'選擇器(x)'給出錯誤「選擇器是一個變量,但像方法一樣使用」。我試過'x => Expression.Invoke(選擇器)+「:」+ Expression.Invoke(選擇器)'但它拋出'InvalidOperationException:爲lambda調用提供的參數數量不正確 – 2011-03-28 15:59:21
@Paul Creasey,這是一個' Expression'。所以你需要在調用之前編譯它:'var myFunc = selector.Compile(); myFunc(x)'或內聯:'selector.Compile()(x)'。答覆已更改。 – NOtherDev 2011-03-28 16:13:20
無法轉換表達式'Table(Finance_RTC_MI_Data).Select(x =>((Invoke(Invoke(value(System.Func'1 [System.Func'2 [com.blah.lvis.Data.DataAccess.Finance_RTC_MI_Data,System。 String)])),x)+「:」)+ Invoke(Invoke(value(System.Func'1 [System.Func'2 [com.blah.lvis.Data.DataAccess.Finance_RTC_MI_Data,System.String]]) ),x)))'到SQL中,並不能把它當作本地表達式。 – 2011-03-28 16:39:01