我開始與此:通Func鍵<>選擇
query
.Take(20)
.Select(item => new
{
id = item.SomeField,
value = item.AnotherField
})
.AsEnumerable()
.ToDictionary(item => item.id, item => item.value);
現在,我想重用的一切,除了SomeField
和AnotherField
。
public static Dictionary<int, string> ReusableMethod<T>(
this IQueryable<T> query,
Func<T, int> key,
Func<T, string> value)
{
return query
.Take(20)
.Select(item => new
{
id = key(item),
value = value(item)
})
.AsEnumerable()
.ToDictionary(item => item.id, item => item.value);
}
query.ReusableMethod(item => item.SomeField, item => item.AnotherField);
這工作,但DB查詢選擇比需要更多的數據,所以我想這意味着ReusableMethod
使用LINQ到對象。
是否有可能做到這一點,而只選擇需要的數據?我會補充一點,Func <>對我來說仍然是魔術,所以我可能會錯過一些明顯的東西。
澄清爲避免混淆:Take(20)
是好的,Select()
不是。
所有字段因爲你'Func'調用不能在SQL進行評估,從而整個對象被選中,函數被調用的對象。 –
@WillemDuncan你是否暗示這是不可能的,或者是否有辦法獲得理想的結果? – Stijn