You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 09:58:19