英文:
How dynamic or usage in EF Core Where?
问题
f.XNumber.Contains(item) or
f.XNumber.Contains(item) or
f.XNumber.Contains(item) or
英文:
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
答案1
得分: 2
使用 LINQKit 的 `PredicateBuilder`
```cs
var predicate = PredicateBuilder.New(query);
foreach (var item in arr)
{
predicate = predicate.Or(f => f.XNumber.Contains(item));
}
query = query.Where(predicate);
或者我的扩展 FilterByItems
query = query.FilterByItems(arr, (f, item) => f.XNumber.Contains(item), true);
英文:
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);
答案2
得分: 1
你在那里做的是向查询添加多个 Where 子句。Entity Framework 然后将它们组合成一个单独的 Where 子句,显然是由 AND 连接的。
所以你需要使用内部谓词并将其添加到查询的单个 Where 子句中。
英文:
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.
答案3
得分: 0
可以用单个 Where
来实现,类似于这样:
query.Where(f => item.Any(i => f.XNumber.Contains(i)))
这将检查是否可以在数组中至少找到一个项目的匹配项。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论