如何用Linq(非Lambda)实现:列表非空则过滤,否则返回全部结果?
解决方案
直接修改查询的where条件,加入对usersStores是否为空的判断即可实现需求,无需大幅改动原有代码结构:
public void Example(userId = ""){ var usersStores = new List<short>(); if(userId != "") usersStores = GetStores(userId); var query = from t in _dbContext.FakeTable where !usersStores.Any() || usersStores.Contains(t.storeId) select new ExampleObject { id = t.storeId, text = t.storeId + " (" + t.storeCity + ")" }; }
逻辑说明
- 当
usersStores为空列表时,!usersStores.Any()返回true,整个where条件直接成立,查询会返回FakeTable中的所有记录; - 当
usersStores包含元素时,!usersStores.Any()返回false,此时会执行usersStores.Contains(t.storeId)的过滤逻辑,只返回用户关联的店铺数据。
这种写法完全保留了原有查询的后续处理流程,仅调整过滤条件即可满足需求。
内容的提问来源于stack exchange,提问作者HumanHickory
相关产品推荐
相关产品推荐

