如何将这段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就是原查询里的fubendictWhere子句对应原查询的过滤条件,筛选内层字典中值列表包含npc.ID的项Select子句对应原查询的select,返回包含副本名和位置的元组
内容的提问来源于stack exchange,提问作者Ventulus
相关产品推荐
相关产品推荐

