LINQ/投影-包含所有用于过滤的通配符
本文关键字:用于 过滤 通配符 投影 -包 LINQ | 更新日期: 2023-09-27 18:17:28
是否有与Contains(")等价的"*" ?我正在使用一些通配符进行过滤,如果没有应用过滤器,那么我需要返回所有?
string[] filter = {1,2}; // This is dynamic could be filtered values or {} empty.
// This works for filtering by products (1,2)
db.Products.Where(x => filter.Contains(x.ProdId));
我真正需要实现的是这样的东西:
// If the filter is empty get all results...if there is a filter passed the filter values in for select
db.Products.Where(x => x.ProdId.Contains(filter.Length == 0 ? "*" : filter);
如果需要,可以直接添加where:
var query = db.Products.AsQueryable();
if (filter.Any())
query = query.Where(x => filter.Contains(x.ProdId));
// use query as needed
使用
var result = db.Products.AsQueryable();
if(filter.Any())
result = result.Where(x => filter.Contains(x.ProdId));
如果过滤器不是唯一的where条件,那根本不是问题,您可以为您的查询定义多个Where
:
var result = db.Products.Where(x => SomeCondition(x));
if(filter.Any())
result = result.Where(x => filter.Contains(x.ProdId));
db.Products.Where(x => !filter.Any() || filter.Contains(x.ProdId))
尽管我喜欢列出的其他答案:
if(filter.Any())
result = result.Where(x => filter.Contains(x.ProdId));
在第一个示例中,它将循环遍历集合并确定过滤器对结果中的每个项都有项。第二个将只在过滤器