如何在Dictionary<int, List<string>>中通过Lambda按List首元素查询对应Key
实现方案
首先需确保项目已引入System.Linq命名空间。
测试数据构造(和你给出的示例一致)
Dictionary<int, List<string>> 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"}} };
核心Lambda分组代码
var groupedResult = taskList // 过滤空List/无元素的条目,避免索引越界异常,不需要可以删除该行 .Where(kv => kv.Value != null && kv.Value.Count > 0) // 按List第0位元素分组,分组内保存对应Task ID(字典Key) .GroupBy(kv => kv.Value[0], kv => kv.Key);
格式化输出代码
foreach (var group in groupedResult) { Console.WriteLine($"Value: \"{group.Key}\"\tTask Id: {string.Join(", ", group)}"); }
运行输出结果
和你需要的效果完全一致:
Value: "2" Task Id: 1664003 Value: "1" Task Id: 1664004, 1664005
内容的提问来源于stack exchange,提问作者saghar francis
相关产品推荐
相关产品推荐

