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

如何将这段C# LINQ查询语法转换为Lambda方法语法?

LINQ查询语法转Lambda方法语法实现

以下是将原查询语法转换为Lambda方法语法的代码,同时做了性能优化:

public Dictionary<string, Dictionary<int, List<int>>> fuBenNPCDictionary;
// ...其他业务代码
IEnumerable<(string fuben, int pos)> query = fuBenNPCDictionary
    .SelectMany(fubenKvp => 
        fubenKvp.Value
            .Where(posKvp => posKvp.Value.Contains(npc.ID))
            .Select(posKvp => (fuben: fubenKvp.Key, pos: posKvp.Key))
    );

if (query.Any()) // 用Any()替代Count()>0,无需遍历全部元素,性能更优
    foreach ((string fuben, int pos) in query)
    {
        placestr = $"在{jsonData.instance.SceneNameJsonData[fuben]["MapName"].str.ToCN()}的第{pos}位置";
    }

转换说明

  • SelectMany 对应原查询里的两层from,用于扁平化嵌套字典的遍历,把外层字典的每个键值对与内层符合条件的项关联起来
  • fubenKvp 等价于原查询中的fuben键对应的键值对,fubenKvp.Value就是原查询里的fubendict
  • Where 子句对应原查询的过滤条件,筛选内层字典中值列表包含npc.ID的项
  • Select 子句对应原查询的select,返回包含副本名和位置的元组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:20:28