PAYATHON 2026

VB.NET Dictionary 如何按多个键字段查找并更新多个值?

数据小许

结论

可以用 Key1 和 Key2 都已赋值的 TestKeys 结构作为查找键,再通过 TryGetValue 读取对应的 TestValues。更新时要注意,TestValues 是结构体,取出后得到的是副本。修改副本后,需要将它重新赋回字典。

题目中的字典定义和添加方式如下:

Dim Test As New Dictionary(Of TestKeys, TestValues)

Test.Add(
    New TestKeys() With {.Key1 = "xx", .Key2 = "yy"},
    New TestValues() With {
        .Value1 = False,
        .Value2 = 0,
        .Value3 = 0,
        .Value4 = 0,
        .Value5 = 0
    })

按两个键字段查找

创建字段值相同的 TestKeys,然后调用 TryGetValue:

Dim key As New TestKeys() With {
    .Key1 = "xx",
    .Key2 = "yy"
}

Dim values As TestValues

If Test.TryGetValue(key, values) Then
    Console.WriteLine(values.Value1)
    Console.WriteLine(values.Value2)
Else
    Console.WriteLine("没有找到匹配的记录")
End If

查找时,Key1 和 Key2 都要与字典中存储的键相符。TestKeys 是结构体,如果没有自定义相等比较,.NET 会按字段值比较。因此,用相同的 Key1 和 Key2 创建查找键即可。

修改已有记录

TryGetValue 返回的 values 是 TestValues 的副本。修改后,将它写回对应的键:

Dim key As New TestKeys() With {
    .Key1 = "xx",
    .Key2 = "yy"
}

Dim values As TestValues

If Test.TryGetValue(key, values) Then
    values.Value1 = True
    values.Value2 = 1.5F

    Test(key) = values
End If

Test(key) = values 会更新该键对应的值。若键不存在,通过索引器赋值会抛出 KeyNotFoundException,因此应先检查键是否存在,或使用 TryGetValue。

注意事项

  • 查找时要同时提供 Key1 和 Key2,并确保它们的值与添加记录时一致。
  • 如果为 TestKeys 自定义了相等比较,也要实现相匹配的哈希码逻辑,否则字典查找可能无法按预期工作。
  • 字典中的键应保持稳定。如果键类型改为包含可变引用对象,加入字典后应避免修改会影响相等比较或哈希码的内容。

备注:内容仅供参考。