c# - 使用 LINQ 从字典中的键获取值列表
问题描述
我编写了下面的代码以从具有给定键的字典中获取所有值。
Dictionary<string,string> _dictionary;
public List<string> GetValuesUsingKey(string key)
{
List<string> outp = new List<string>();
foreach(var d in _dictionary)
{
if (d.Key == key)
{
outp.Add(d.Value);
}
}
return outp;
}
有没有更简单的方法可以使用 LINQ 实现此结果?
更新 :
原来我对字典有误解,虽然我可以为一个键使用多个值但我错了
解决方案
a 中的键Dictionary
保证是唯一的,因此无需返回 a List
。
public string GetValueUsingKey(string key)
{
bool isKeyPresent = _dictionary.TryGetValue(key, out var output);
return isKeyPresent ? output : _YOUR_DEFAULT_BEHAVIOUR_;
}
a 的最大优点Dictionary
是使用键插入和检索值的时间复杂度是O(1)
; 如果您循环浏览KeyValuePair
它包含的所有内容,您将完全取消使用 a 的目的,Dictionary
因为它会进行检索O(n)
!
推荐阅读
- linux - mktemp:无法通过模板“/tmp/virtualenvwrapper-initialize-hook-XXXXXXXXXX”创建文件:只读文件系统
- sql - 如何根据 Athena (Presto) 中的列值将一行分成多行?
- elasticsearch - ElasticSearch:如何读取 _node/hot_threads 的输出
- python - 尽管来自 API 的 200,但在 Google 表格上添加权限不起作用
- python - 使用 BeautifulSoup 和 Selenium 从表中抓取数据
- c# - 如何使用 NEST(C#) 在 Elasticsearch 中上传/索引 GeoJson 文件
- npm - 在 package.json 中提升一个文件包的依赖
- javascript - 需要关于解析多级 JSON 的帮助
- python - python的多行微调器?
- google-apps-script - app脚本文件上传返回文件url到Html页面