LINQ中的参数动态“不”(或任何其他代码)

时间:2009-05-18 19:31:50

标签: c# linq parameters

好,

这可能非常简单,甚至可能无法实现,或者我只是大脑冻结了:)

这是我想要做的一个例子:

public void SomeMethod(bool include)
        {
            using (AccountDataContext db = AccountContextFactory.CreateContext())
            {
                if (include)
                {
                    var query = from a in db.FundingTypes where a.FundingTypeId == 1 select a;
                }
                else
                {
                    var query = from a in db.FundingTypes where a.FundingTypeId != 1 select a;
                }
            }
        }

我想动态更改!=和=而不必编写全新的查询。我在现实生活中使用的查询非常大,我不喜欢代码重复。

思想还是想法?

由于

5 个答案:

答案 0 :(得分:11)

这看起来非常简单。

var predicate = include ? 
  (Func<int, bool>) x=>x == 1 : 
  (Func<int, bool>) x=>x != 1 ;
var query = from a in db.FundingTypes where predicate(a.FundingTypeId) select a;

答案 1 :(得分:2)

这个怎么样:

var query = 
    from a in db.FundingTypes 
    where (a.FundingTypeId == 1) == include 
    select a;

答案 2 :(得分:0)

这个怎么样:

public void SomeMethod(bool include, Func<int, bool> query)
{
    using (AccountDataContext db = AccountContextFactory.CreateContext())
    {
         var query = from a in db.FundingTypes where query(a.FundingTypeId) select a;
    }
}

答案 3 :(得分:0)

试试这个:

SomeMethod(bool include)
{
    using (AccountDataContext db = AccountContextFactory.CreateContext())
    {
        var query = from a in db.FundingTypes where !include ^ (a.FundingTypeId == 1) select a;
    }
}

编辑使用XOR

简化逻辑

答案 4 :(得分:0)

试试这个:

var predicate = include
    ? (Func<FundingType, bool>) f => f.FundingTypeId == 1
    : (Func<FundingType, bool>) f => f.FundingTypeId != 1
return (from a in db.FundingTypes select a).Where(predicate);