10

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

 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
 }
4

5 回答 5

14

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

where keys.All(key => feed.content.contains(key))
于 2013-01-14T14:17:44.100 回答
7

对于 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 {....});
于 2013-01-14T14:21:42.793 回答
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 })
于 2013-01-14T14:14:17.493 回答
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)
于 2013-01-14T14:19:31.273 回答
2

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

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

/// <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);
}

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

于 2017-03-29T18:56:43.607 回答