如何用C#函数式/LINQ实现字典查找的所有匹配结果列表返回?
问题分析与解决方案
你的LINQ实现存在两个核心问题:
- Select逻辑错误:
characters.Select(x => dictionary[characters])中,你把整个字符集合characters传给了字典索引器,而非当前遍历的单个字符x,这直接导致逻辑完全偏离预期。 - 未处理不存在的键:直接使用字典索引器
dictionary[x]会抛出KeyNotFoundException,和你原foreach逻辑(仅保留字典中存在的键对应的字符串)不符。
正确的LINQ实现(匹配原foreach逻辑)
string inputString = "//comment"; // 补全字典初始化,原代码遗漏了new操作 Dictionary<char, string> crossRefDict = new Dictionary<char, string>(); crossRefDict.Add('/', "DIVIDE"); crossRefDict.Add('a', "ALPHA"); crossRefDict.Add('b', "ALPHA"); Func<Dictionary<char, string>, IEnumerable<char>, IEnumerable<string>> returnCharRefs = (dictionary, characters) => characters.Where(c => dictionary.ContainsKey(c)) // 对应原代码的if判断,过滤存在的键 .Select(c => dictionary[c]); // 将字符映射为字典中对应的字符串 // string本身实现了IEnumerable<char>,无需额外Select转换 IEnumerable<char> inputCharacters = inputString; IEnumerable<string> characterReferences = returnCharRefs(crossRefDict, inputCharacters); return characterReferences;
优化版(减少字典查询次数)
如果需要避免ContainsKey和索引器两次查询字典的开销,可以用TryGetValue实现,效率更高:
Func<Dictionary<char, string>, IEnumerable<char>, IEnumerable<string>> returnCharRefs = (dictionary, characters) => characters.Select(c => { dictionary.TryGetValue(c, out var value); return value; }) .Where(value => value != null); // 过滤不存在的键对应的null值
额外说明
- 原代码中
crossRefDict未初始化(缺少new Dictionary<char, string>()),会触发NullReferenceException,修正代码已补全。 inputString.Select(x => x)属于冗余操作,string类型本身就实现了IEnumerable<char>,直接赋值即可。
内容的提问来源于stack exchange,提问作者friendlybus
相关产品推荐
相关产品推荐

