1 回答

TA貢獻(xiàn)1810條經(jīng)驗 獲得超4個贊
如果將其表示為where子句,則可以使用LINQ to SQL開箱即用,如果可以構(gòu)造適當(dāng)?shù)谋磉_(dá)式。
就表達(dá)式樹而言,可能有一種更好的方法-Marc Gravell可能會改進(jìn)它-但值得一試。
static class Ext
{
public static IQueryable<TSource> Between<TSource, TKey>
(this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
TKey low, TKey high) where TKey : IComparable<TKey>
{
Expression key = Expression.Invoke(keySelector,
keySelector.Parameters.ToArray());
Expression lowerBound = Expression.GreaterThanOrEqual
(key, Expression.Constant(low));
Expression upperBound = Expression.LessThanOrEqual
(key, Expression.Constant(high));
Expression and = Expression.AndAlso(lowerBound, upperBound);
Expression<Func<TSource, bool>> lambda =
Expression.Lambda<Func<TSource, bool>>(and, keySelector.Parameters);
return source.Where(lambda);
}
}
不過,這可能取決于所涉及的類型-特別是,我使用了比較運算符而不是IComparable<T>。我懷疑這更有可能正確地轉(zhuǎn)換為SQL,但是您可以根據(jù)需要將其更改為使用該CompareTo方法。
像這樣調(diào)用它:
var query = db.People.Between(person => person.Age, 18, 21);
添加回答
舉報