LINQ is it possible to add where clauses dynamically

c# entity-framework linq where-clause

Question

I want to search my db with different keys. According to the input, there may be 1 key to 10 keys. Is there a way to add OR/AND clauses to my Linq query dynamically?

 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
 }
1
8
1/14/2013 2:18:42 PM

Accepted Answer

You could try an .All clause to check all the keys:

where keys.All(key => feed.content.contains(key))
13
1/14/2013 2:17:44 PM

Popular Answer

For AND clauses it is simple:

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 {....});

For OR you will need to use Expressions or try LinqKit and its predicates :

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 {....});


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow