通过键从字典中获取项目
我有这样的结构:
static Dictionary<int, Dictionary<int, string>> tasks =
new Dictionary<int, Dictionary<int, string>>();
看起来
[1]([8] => "str1")
[3]([8] => "str2")
[2]([6] => "str3")
[5]([6] => "str4")
我想从这个列表中获取所有 [8]
字符串,意思是 str1
+ str2
< br> 该方法应如下所示:
static List<string> getTasksByNum(int num){
}
如何访问它?
I have this structure:
static Dictionary<int, Dictionary<int, string>> tasks =
new Dictionary<int, Dictionary<int, string>>();
it looks like that
[1]([8] => "str1")
[3]([8] => "str2")
[2]([6] => "str3")
[5]([6] => "str4")
I want to get from this list all of the [8]
strings, meaning str1
+ str2
The method should look like the following:
static List<string> getTasksByNum(int num){
}
How do I access it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
丹尼尔的解决方案可能是最好的,因为它更容易理解。但也可以在 linq 方法中使用 TryGetValue:
Daniel's solution is probably best, since it's easier to understand. But it's possible to use TryGetValue in a linq approach, too:
您正在构建任务吗?
如果我猜对了,那就是tasks[task_id]([cpu] => "task_name");
我建议您还构建 cpu_tasks[cpu]([task_id] => "task_name);
它需要更多的维护,但会让您更快地运行这个特定的函数。
Are you building tasks ?
And if I'm guessing right it's tasks[task_id]([cpu] => "task_name");
I would advice you also build cpu_tasks[cpu]([task_id] => "task_name);
It would require some more maintenance but would give you a faster run on this specific function.
使用 LINQ,您可以执行以下操作:
虽然这很优雅,但
TryGetValue
模式通常比它使用的两个查找操作更可取(首先尝试ContainsKey
,然后使用索引器来获取值)。如果这对您来说是个问题,您可以执行类似的操作(使用合适的辅助方法):
With LINQ, you can do something like:
While this is elegant, the
TryGetValue
pattern is normally preferable to the two lookup operations this uses (first tryingContainsKey
and then using the indexer to get the value).If that's an issue for you, you could do something like (with a suitable helper method):
只需迭代第一个层次结构级别的所有值,并在第二个级别上使用
TryGetValue
:此解决方案比迄今为止提出的所有其他解决方案具有主要优势:
它实际上使用第二层次结构级别的字典作为字典,即 foreach 循环内的部分是 O(1) 而不是所有其他解决方案的 O(n)。
Just iterate over all values of the first hierarchy level and use
TryGetValue
on the second level:This solution has a major advantage over all other solutions presented so far:
It actually uses the dictionaries of the second hierarchy level as a dictionary, i.e. the part inside the foreach loop is O(1) instead of O(n) as with all other solutions.
检查这个功能:
Check this function: