LINQ是否可以动态添加where子句

时间:2013-01-14 14:10:40

标签: c# linq entity-framework where-clause

我想用不同的密钥搜索我的数据库。根据输入,10键可能有1个键。有没有办法动态地向我的Linq查询添加OR / AND子句?

 keys[k] // I have my keys in this array 
 var feedList = (from feed in ctx.Feed
                 where feed.content.contains(keys[0]) 
                       && feed.content.contains(keys[1])
                       && ... // continues with the keys.length
                 select new {
                    FeedId = feed.DuyuruId,
                    FeedTitle = feed.FeedTitle,
                    FeedContent = feed.FeedContents,
                    FeedAuthor = user.UserName + " " +User.UserSurname
 }

5 个答案:

答案 0 :(得分:12)

您可以尝试.All子句来检查所有键:

where keys.All(key => feed.content.contains(key))

答案 1 :(得分:6)

对于AND子句来说很简单:

var feedList = from feed in ctx.Feed;
foreach(var key in keys){
    feedList = feedList.Where(x=> content.contains(key));
}
var resultQuery = feedList.Select(x=> new {....});

对于OR,您需要使用Expressions或尝试LinqKit及其谓词:

var predicate = PredicateBuilder.False<TypeOfYourEntity>();
foreach(var key in keys){
    predicate = predicate.Or(x=> content.contains(key));
}
var resultQuery = ctx.Feed.Where(predicate).Select(x=> new {....});

答案 2 :(得分:3)

您可以使用LINQ的扩展方法

ctx.Feed.Where(f => {  
//Your logic here
if(something != null){
      return f.Property == something
  } 
}).Select( new { FeedId = feed.DuyuruId,
                    FeedTitle = feed.FeedTitle,
                    FeedContent = feed.FeedContents,
                    FeedAuthor = user.UserName + " " +User.UserSurname })

答案 3 :(得分:2)

你可以这样做。记住它可能会导致一些开销

 var students = ctx.Students;

 if (!String.IsNullOrWhiteSpace(SearchParams.Name))
      students = from s in students where s.Name.StartsWith(SearchParams.Name)

 if (!String.IsNullOrWhiteSpace(SearchParams.Surname))
      students = from s in students where s.Surname.StartsWith(SearchParams.Surname)

答案 4 :(得分:2)

我想提供一个示例,说明@ mellamokb的答案如何适用于我的场景,以帮助任何需要相当动态linq查询的人。

在我的示例中,我只是对datatable类进行了扩展,因此我可以检查数据库中是否存在一行数据,因此不会抛出SQL主键异常。< / p>

/// <summary>
/// 
/// </summary>
/// <param name="DT"></param>
/// <param name="ColumnNames">Columns to check in affected table.</param>
/// <param name="ItemtoChecks">Values to check in affected column.</param>
/// <returns></returns>
public static bool TableContains(this DataTable DT, string[] ColumnNames, object[] ItemtoChecks)
{
  var result = from row in DT.AsEnumerable()
               where ColumnNames.All(
               r => row.Field<object>(r).ToString() == Convert.ToString(
                 ItemtoChecks[ColumnNames.ToList()
                 .FindIndex(p => p.Equals(r, StringComparison.OrdinalIgnoreCase))]))
               select row;                   
  return (result.Count() > 0);
}

此方法允许您根据需要向string[]添加任意数量的列名以及相应的值,以便单独检查object[]。查询将检查datatable,如果找到匹配项,则方法返回true,否则返回false