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

如何在List<Dictionary<string,string>>中引用下一个字典重组数据?

解决方案

首先,你的原始数据是每两个字典为一组:第一个字典包含时间和Player1的信息,第二个字典包含Player2的信息。要合并成目标格式,核心思路就是按步长为2的方式遍历原始列表,每次同时取当前索引和下一个索引的字典,然后合并成新的字典——这和你PHP里用索引+1的思路本质完全一致,只是语法上适配当前环境即可。

具体实现步骤

  • 初始化一个空的List<Dictionary<string, string>>来存储最终结果
  • 使用for循环遍历原始列表,循环变量从0开始,每次递增2(确保每次处理一组两个字典)
  • 每次循环中:
    1. 取出当前索引i的字典(包含时间和Player1的数据)
    2. 取出索引i+1的字典(包含Player2的数据)
    3. 创建新字典,从两个源字典中提取需要的字段并映射到目标键名
    4. 将新字典加入结果列表
  • 额外判断:如果原始列表长度为奇数,提前终止循环避免索引越界(可根据需求处理最后一个多余元素)

代码示例(C#环境)

// 模拟你的原始列表
var originalList = new List<Dictionary<string, string>>()
{
    new Dictionary<string, string>() { ["Cell1"] = "10:00", ["Cell2"] = "Player1Name", ["Cell3"] = "P1Score", ["Cell4"] = "P1ImpliedChance" },
    new Dictionary<string, string>() { ["Cell1"] = "Player2Name", ["Cell2"] = "P2Score", ["Cell3"] = "P2ImpliedChance" },
    new Dictionary<string, string>() { ["Cell1"] = "12:00", ["Cell2"] = "Player1Name", ["Cell3"] = "P1Score", ["Cell4"] = "P1ImpliedChance" },
    new Dictionary<string, string>() { ["Cell1"] = "Player2Name", ["Cell2"] = "P2Score", ["Cell3"] = "P2ImpliedChance" }
};

var resultList = new List<Dictionary<string, string>>();

// 按步长2遍历原始列表
for (int i = 0; i < originalList.Count; i += 2)
{
    // 防止索引越界(如果列表长度为奇数)
    if (i + 1 >= originalList.Count)
        break;

    var timePlayer1Dict = originalList[i];
    var player2Dict = originalList[i + 1];

    // 构建目标格式的新字典
    var mergedDict = new Dictionary<string, string>()
    {
        ["Cell1"] = timePlayer1Dict["Cell1"],
        ["Cell2"] = timePlayer1Dict["Cell2"],
        ["Cell3"] = player2Dict["Cell1"],
        ["Cell4"] = timePlayer1Dict["Cell4"],
        ["Cell5"] = player2Dict["Cell3"]
    };

    resultList.Add(mergedDict);
}

// 验证输出(可选)
foreach (var dict in resultList)
{
    foreach (var kvp in dict)
    {
        Console.WriteLine($"{kvp.Key}: {kvp.Value}");
    }
    Console.WriteLine("---");
}

关键说明

  • 这种方法完全不需要修改原始数据结构,所有操作基于遍历和新对象创建
  • 不管你用的是C#还是其他.NET系语言,核心逻辑都是通过控制循环索引的步长,直接访问下一个元素(i+1),和你熟悉的PHP思路完全对齐
  • 如果需要处理更复杂的分组规则(比如每组数量不固定),可以先给原始列表做分组标记,再按组合并,但当前场景下步长遍历是最高效的方式

内容的提问来源于stack exchange,提问作者RevasEfil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:35:39