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
}
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.
A single query expression may have multiple where clauses.
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.
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 {....});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With