1

日時を含むオブジェクトがいくつかあります。ラムダステートメントを再利用していることがわかりました。

Where(x => EntityFunctions.TruncateTime(x.Date.Value) >= EntityFunctions.TruncateTime(startDate) &&
    EntityFunctions.TruncateTime(x.Date.Value) <= EntityFunctions.TruncateTime(endDate));

多くの場所で。この式を、日付のあるオブジェクトのリストで使用できる単一の述語に置き換えたいと思います。

4

3 に答える 3

1

YourType正しい日付があるかどうかをチェックする別の述語メソッドを定義します

private static bool IsObjectHasNeccesaryDate(YourType obj, DateTime startDate, DateTime endDate)
{
    return EntityFunctions.TruncateTime(obj.Date.Value) >= EntityFunctions.TruncateTime(startDate) 
        && EntityFunctions.TruncateTime(obj.Date.Value) <= EntityFunctions.TruncateTime(endDate);
}

次に、次のようにラムダ構文を使用して使用できます。

myobjects.Where(obj => IsObjectHasNeccesaryDate(obj, startDate, endDate));

startDateendDate変数をキャプチャすることに注意してください。

于 2013-03-15T17:09:30.443 に答える
1

式をFuncとして定義できます。

Func<object,bool> exp = x => 
    EntityFunctions.TruncateTime(x.Date.Value) >= EntityFunctions.TruncateTime(startDate) 
    && EntityFunctions.TruncateTime(x.Date.Value) <= EntityFunctions.TruncateTime(endDate);

オブジェクトを、使用しているタイプに置き換えます。次に、FuncをWhereに渡します。

Where(exp);
于 2013-03-15T17:11:32.463 に答える
1

startDateおよびがクラスレベルの変数である場合endDateは、次のメソッドを使用できます。

bool FilterDate(YourEntityType x)
{
    return EntityFunctions.TruncateTime(x.Date.Value) >= EntityFunctions.TruncateTime(startDate) &&
           EntityFunctions.TruncateTime(x.Date.Value) <= EntityFunctions.TruncateTime(endDate));
}

これは、次の方法で呼び出されます。

var results = myobjects.Where(FilterDate);

ただし、それらがローカルの場合、ラムダは2つのローカル変数(startDateおよびendDate)を閉じているため、スコープが常に同じに保たれていない限り、単一のデリゲートを再利用すると動作が変わる可能性があります。

1つのオプションは、ヘルパーメソッドを作成することです。

static Func<YourEntityType, bool> CreateFilter(DateTime startDate, DateTime endDate)
{
     Func<YourEntityType, bool> func = x => EntityFunctions.TruncateTime(x.Date.Value) >= EntityFunctions.TruncateTime(startDate) &&
EntityFunctions.TruncateTime(x.Date.Value) <= EntityFunctions.TruncateTime(endDate));
     return func;
}

次に、これを次のように書くことができます。

var results = myobjects.Where(CreateFilter(startDate, endDate));
于 2013-03-15T17:16:35.403 に答える