Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ is it possible to add where clauses dynamically

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
 }
like image 975
tkcn Avatar asked Jan 14 '13 14:01

tkcn


People also ask

Can you use LINQ on dynamic?

The Dynamic source file includes a helper library that allows you to express LINQ queries using extension methods that take string arguments instead of type safe operators. To use the Dynamic Expression API, you could simply copy/paste the Dynamic source file in your project.

Can we use multiple where clause in LINQ query?

A single query expression may have multiple where clauses.

What is where clause in LINQ?

The where clause is used in a query expression to specify which elements from the data source will be returned in the query expression. It applies a Boolean condition (predicate) to each source element (referenced by the range variable) and returns those for which the specified condition is true.


1 Answers

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 {....});
like image 163
mipe34 Avatar answered Nov 15 '22 16:11

mipe34