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

如何将两层for循环改写为单条LINQ语句?

两层for循环转LINQ语句解决方案

我搞不清楚怎么把下面的两层for循环改写成单条LINQ语句,求帮忙解决。

原代码

var CleanerAccounts = new List<Account>();
var array = _context.Accounts.Include(x => x.UserFunctions).ToArray();
for (int i= 0; i < array.Length; i++)
{
    foreach(Function f in  array[i].UserFunctions)
    {
        if(f.UserFunction.Equals("Cleaner"))
        {
            CleanerAccounts.Add(array[i]);
            break;
        }
    }
}

这段代码的核心逻辑是:从数据库上下文加载所有关联了UserFunctions的Account,遍历每个Account,只要其关联的UserFunctions中存在任意一个UserFunction属性等于"Cleaner"的项,就将该Account加入结果列表,且找到匹配后立即停止遍历当前Account的UserFunctions。

可运行的LINQ版本

var cleanerAccounts = _context.Accounts
                              .Include(x => x.UserFunctions)
                              .Where(account => account.UserFunctions
                                                       .Any(uf => uf.UserFunction.Equals("Cleaner")))
                              .ToArray();

逻辑对应说明

  • Include(x => x.UserFunctions) 保留原逻辑,用于预加载Account关联的UserFunctions数据
  • Where 方法筛选符合条件的Account,其中account.UserFunctions.Any(...) 完美对应原代码中“找到第一个匹配项就停止遍历并加入结果”的逻辑——Any方法会在检测到第一个匹配元素时立即终止遍历,和原代码里的break行为一致
  • 最后通过ToArray()直接生成结果数组,无需手动初始化列表并逐个添加元素

内容的提问来源于stack exchange,提问作者rejkid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:24:58