Sex*_*yMF 4 c# dictionary multi-level
我有这个结构:
static Dictionary<int, Dictionary<int, string>> tasks =
new Dictionary<int, Dictionary<int, string>>();
Run Code Online (Sandbox Code Playgroud)
它看起来像那样
[1]([8] => "str1")
[3]([8] => "str2")
[2]([6] => "str3")
[5]([6] => "str4")
Run Code Online (Sandbox Code Playgroud)
我想从这个列表中获取所有[8]字符串,意思是str1+ str2
该方法应如下所示:
static List<string> getTasksByNum(int num){
}
Run Code Online (Sandbox Code Playgroud)
我该如何访问它?
使用LINQ,您可以执行以下操作:
return tasks.Values
.Where(dict => dict.ContainsKey(8))
.Select(dict => dict[8])
.ToList();
Run Code Online (Sandbox Code Playgroud)
虽然这很优雅,但TryGetValue模式通常比它使用的两个查找操作更好(首先尝试ContainsKey然后使用索引器来获取值).
如果这对你来说是一个问题,你可以做一些事情(使用合适的帮助方法):
return tasks.Values
.Select(dict => dict.TryGetValueToTuple(8))
.Where(tuple => tuple.Item1)
.Select(tuple => tuple.Item2)
.ToList();
Run Code Online (Sandbox Code Playgroud)