[英]How to search for the keys from dictionary of <int, List<string>>
我有字典Dictionary<int, List<string>> taskList = new Dictionary<int, List<string>>();
这给了我这样的结果:
Task ID: 1664003 Values:
"2"
"5"
"1"
"4"
"3"
Task ID: 1664004 Values:
"1"
"2"
"3"
"5"
"4"
Task ID: 1664005 Values:
"1"
"2"
"5"
"4"
"3"
现在我想搜索对值的零索引的键,如下所示:
Values: "2" Task Id: 1664003
Value: "1" Task Id: 1664004, 1664005
我想使用 lambda 表达式来实现它
您需要遍历字典的每个条目,获取列表的第一项并将其与您要查找的内容进行比较,如下所示:
var search = 1;
var dictionary = // your dictionary
var output = new List<int>();
foreach (var kvp in dictionary)
{
if (kvp.Value.First() == search)
output.Add(kvp.Key);
}
Console.WriteLine($"The following tasks have the value {search} in the dictionary:");
foreach (var result in output)
Console.WriteLine(result);
PS 您可能想重新考虑您的数据结构,因为这似乎是对字典的误用
对于这种搜索,您的字典是错误的方式。 考虑创建一个正确的字典,然后多次搜索
var d = new Dictionary<int, List<string>>()
{
{ 1664003, new List<string>() {"2","5","1","4","3"}},
{ 1664004, new List<string>() {"1","2","3","5","4"}},
{ 1664005, new List<string>() {"1","2","5","4","3"}}
};
//invert the dictionary (only take first element of each list)
var dRev = d.GroupBy(kvp => kvp.Value.First(), kvp => kvp.Key)
.ToDictionary(g => g.Key, g => g.ToList());
//now you can search it many times
var x = dRev["1"]; //x is a list containing {1664004,1664005}
var y = dRev["2"]; //y is a list containing {1664003}
理想情况下,只要合理可行,您就可以保留dRev
; 如果您要批量进行大量搜索,则重建它是有意义的。 每次搜索单个项目时都没有必要重新构建它,但也许可以考虑采用构建您现在拥有的字典的东西并将其添加到其中,以便它也构建一个反向字典,如果您要在此中搜索方向经常,但一次一个项目。
如果您的搜索只在这个方向上,您的字典可能完全是错误的,并且维护它的东西应该重新设计以永久反转它
class Program
{
static void Main(string[] args)
{
var taskList = new Dictionary<int, List<string>>()
{
{ 1664003, new List<string>() {"2","5","1","4","3"}},
{ 1664004, new List<string>() {"1","2","3","5","4"}},
{ 1664005, new List<string>() {"1","2","5","4","3"}}
};
var list = taskList.ToList();
var searchKey = "1";
var keys = list.Where(x=> x.Value[0] == searchKey).Select(x => x.Key).ToList();
var result = string.Join(",", keys);
}
}
Dictionary<int, List<string>> taskList = new Dictionary<int, List<string>>();
List<string> list1 = new List<string>() { "2", "5", "1", "4", "3" };
List<string> list2 = new List<string>() { "1", "2", "3", "5", "4" };
List<string> list3 = new List<string>() { "1", "2", "5", "4", "3" };
taskList.Add(1664003, list1);
taskList.Add(1664004, list2);
taskList.Add(1664005, list3);
string search = "1";
var result = new List<int>();
foreach (var kvp in taskList)
{
if (kvp.Value[0] == search)
result.Add(kvp.Key);
}
Console.WriteLine($"Output: {string.Join(", ", result)}");
输出:
Output: 1664004, 1664005
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.