1

私は次の機能を持っています

public virtual ICollection<T> initData<T>(System.Data.Entity.DbSet<T> set, System.Linq.Expressions.Expression<Func<T, bool>> filter) where T : CModel<T>
        {
            var x = (from dc in set select dc);
            if (!this.db.valid)
            {
                System.Linq.Expressions.Expression<Func<T, bool>> active = a => a.active;
                filter = (Expression<Func<T, bool>>)Expression.Lambda(Expression.AndAlso(filter, active));
                x.Where(filter);

            }
            else
            {
                x.Where(filter);
            }
            return (ICollection<T>)x.ToList();
        }

2 つの述語を組み合わせようとすると、常にAndAlso例外がスローされます。

The binary operator AndAlso is not defined for the types 'System.Func`2[namespace.Models.MyClass,System.Boolean]' and 'System.Func`2[namespace.Models.MyClass,System.Boolean]'.

これら2つの条件をどのように組み合わせることができますか?

4

1 に答える 1

1

あなたは自分の人生を苦しめていると思います。次のように Where 拡張メソッドを複数回使用できます。

public virtual ICollection<T> initData<T>(System.Data.Entity.DbSet<T> set, System.Linq.Expressions.Expression<Func<T, bool>> filter) where T : CModel<T>
{
    var x = (from dc in set select dc);
    x = set.Where(filter);

    if (!this.db.valid)
    {
        x = x.Where(a => a.active);
    }

    return x.ToList();
}

x.Where(filter);
使用したコードでは、Where は x を変更しないため、これは役に立たないことに注意してください。結果は基本的に破棄されます。結果を保持するには、何かに割り当てる必要があります: x = x.Where(filter);.
これは、文字列を操作するときと同じ考え方です。

 

2番目の答え:

と呼ばれるデリゲートが組み込まれていPredicate<T>ます。Func<T, bool>どちらも本質的には同じ意味ですが、よりもこのタイプを使用した方が運が良いと思います。それがコンパイラエラーが言おうとしていたことだと思います。

于 2013-02-10T11:09:41.730 に答える