1

My sample code block is as follows, I have a string array. This array consists of dynamically not predetermined

var query = _dbContext.Table..;
List<string> arr= ...;
// output: arr=X,Y,Z

foreach (var item in arr)
{
    query = query.Where(f => f.XNumber.Contains(item))
}

The output of the expression I want to do should be like this

f.XNumber.Contains(item) or 
f.XNumber.Contains(item) or 
f.XNumber.Contains(item) or 

but every where causes an and operator. How can I convert it to OR operator? Is there a method like WhereWithOr?

Edit: my data looks like this:

XNumber:
12331X,
5113Y,
5123,
Z5123,
...

I'm trying to find items containing X or Y and Z in field XNumber

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • What is preventing you from using the `||` operator? – Peter Bruins May 17 '23 at 09:06
  • I am creating a query dynamically. Something like this is not possible foreach(){ query=query.Where(f=>f.XNumber(item) || ) } – Zafer Kırık May 17 '23 at 09:08
  • You might want to turn the query around if possible, and do something like `.Where(f => arr.Contains(f.XNumber))`, that should be translated to an [sql in](https://www.w3schools.com/sql/sql_in.asp) operator. – JonasH May 17 '23 at 09:30

3 Answers3

1

Using LINQKit's PredicateBuilder

var predicate = PredicateBuilder.New(query);
foreach (var item in arr)
{
    predicate = predicate.Or(f => f.XNumber.Contains(item));
}
query = query.Where(predicate);

Or my extension FilterByItems

query = query.FilterByItems(arr, (f, item) => f.XNumber.Contains(item), true);
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
1

What you're doing there is adding multiple Where clauses to the query. EF then combines them into a single Where claure that, obviously, joined by ANDs.

So youdneed to work with the inner predicate and add that to a single Where in your query.

An answer here suggests using PredicateBuilder

gbjbaanb
  • 51,617
  • 12
  • 104
  • 148
0

It could be done with a single Where, something like this:

query.Where(f => item.Any(i => f.XNumber.Contains(i)))

This will check if it can find a match for at least 1 item in your array.

Peter Bruins
  • 807
  • 9
  • 25
  • 1
    Thank you for the answer "could not be translated. Either rewrite the query in a form that can be translated" With iqueryable this is not possible – Zafer Kırık May 17 '23 at 09:21