C# 创建动态Where子句作为Linq表达式

C# 创建动态Where子句作为Linq表达式,c#,linq,linq-to-sql,C#,Linq,Linq To Sql,我试图动态地将where条件附加到单个表达式对象中,然后将该表达式对象传递到将使用它的方法中。然而,我不断得到“类名此时不可用” 提前谢谢 更新: 我终于能够创建一个新的 代码如下所示: var view = new vw_QuickFindResult(); // This wont compile Expression<Func<vw_QuickFindResult, bool>> where = Expression<Func<v

我试图动态地将where条件附加到单个表达式对象中,然后将该表达式对象传递到将使用它的方法中。然而,我不断得到“类名此时不可用”

提前谢谢

更新:
我终于能够创建一个新的

代码如下所示:

    var view = new vw_QuickFindResult();

   // This wont compile
    Expression<Func<vw_QuickFindResult, bool>> where = Expression<Func<vw_QuickFindResult, bool>>(view, true);

    // Build LIKE Statement
    var searches = new List<String>(searchText.Split(' '));
    searches.ForEach(productName =>
    {
        productName.Replace('"', '%');
        productName.Replace('*', '%');
        where = x => SqlMethods.Like(view.DocumentName, productName);
    });

    return DocumentCollectionService.ListQuickFind(where);
var view=new vw_QuickFindResult();
//这不会编译
表达式,其中=表达式(视图,true);
//类构建语句
var searches=新列表(searchText.Split(“”));
searches.ForEach(productName=>
{
productName.Replace(“,%”);
productName.Replace(“*”、“%”);
其中=x=>SqlMethods.Like(view.DocumentName,productName);
});
返回DocumentCollectionService.ListQuickFind(其中);
这是一个问题:

where = x => SqlMethods.Like(view.DocumentName, productName);
您在这里忽略了
x
,而使用了刚刚初始化的
视图。我怀疑您想要:

where = x => SqlMethods.Like(x.DocumentName, productName);
但是,这将每次替换现有的
where
表达式。我认为您应该使用Joe Albhari。我个人也会避免使用
ForEach

var where = PredicateBuilder.False<vw_QuickFindResult>();

// Build LIKE Statement
foreach (string productName in searchText.Split(' '))
{
    string like = productName.Replace('"', '%');
                             .Replace('*', '%');
    where = where.Or(x => SqlMethods.Like(view.DocumentName, like));
}

return DocumentCollectionService.ListQuickFind(where);
var其中=PredicateBuilder.False();
//类构建语句
foreach(searchText.Split(“”)中的字符串productName)
{
字符串like=productName.Replace(“”,“%”);
。取代(“*”、“%”);
where=where.Or(x=>SqlMethods.Like(view.DocumentName,Like));
}
返回DocumentCollectionService.ListQuickFind(其中);

(我在猜测您想要的功能;您可能想要
PredicateBuilder.True
扩展方法。)

这太棒了!问:如果我还想创建一个动态OrderBy怎么办?@PrisonerZERO:这会变得更加棘手,因为您还需要对目标属性类型进行排序。在大多数情况下,如果有一组固定的订单,我怀疑switch语句是实现这些订单的最简单方法。谢谢!我对Linq-to_SQL完全陌生,这真的为我节省了很多时间。