3

LINQ to Entities を使用して、特定の日付期間内のエントリをクエリしています。これは、プロパティを持つモデル オブジェクトに保持されDateFromDateTo. これを行うには、次を使用してシーケンスを作成します

var allActiveLogs = this.repository.RoutePerformanceLogs
         .Where(log => log.Date >= model.DateFrom.Value && 
                log.Date <= model.DateTo.Value)

これを抽象化して再利用したい場合は、次の式を作成できます (モデルがスコープ内にある場合)。

Expression<Func<RoutePerformanceLog, bool>> logWithinDateBounds = log => 
        log.Date >= model.DateFrom.Value && log.Date <= model.DateTo.Value;

そして後で電話する

var allActiveLogs = this.repository.RoutePerformanceLogs.Where(logWithinDateBounds)

私がやりたいのは、この式をさらに抽象化し、モデルがスコープ外の場所でコード化することです。おそらく署名の式を使用します

Expression<Func<RoutePerformanceLog, DateTime?, DateTime?, bool>> logWithinDateBounds

Func<T, boolean>ただし、 where メソッドにはまたはが必要なため、これは Where メソッド内では機能しませんExpression<Func<T, boolean>>

複数のパラメーターを取り、IQueryableコレクションをフィルター処理するために使用できる再利用可能な式を作成することは可能ですか (メモリ内のオブジェクトをフィルター処理するのではなく、クエリ プロバイダーを使用してフィルター処理を行うことをお勧めします)。

4

1 に答える 1

2

これが役立つことを願っています。これは非常に機能的なプログラミング手法です。関数を返す関数 (または式) を作成し、その関数を Where に使用できます。

次のようなもの:

Func<int, int, Func<int,bool>> func = (x, y) => z=> x + y > z;
var list = new List<int> { 1, 2, 3, 4, 5, 6 };

Console.WriteLine("How many greater than 2+1? {0}", 
                  list.Where(func(1, 2)).Count());
Console.WriteLine("How many greater than 3+1? {0}", 
                  list.Where(func(3, 1)).Count());
Console.WriteLine("How many greater than 2+3? {0}", 
                  list.Where(func(2, 3)).Count());
Console.ReadKey();

あなたの場合、必要なもの:

Func<DateTime, DateTime, Expression<Func<RoutePerformanceLog, bool>>> logWithinDateBounds =         
    (dateFrom, dateTo) => 
       log => log.Date >= dateFrom && log.Date <= dateTo;
于 2012-08-03T09:22:54.893 に答える