You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:54:08