c# 两个key 对应一个 value
时间: 2024-03-05 17:50:38 浏览: 13
在C#中,可以使用自定义类型作为字典(Dictionary)的键,这个自定义类型包含两个key字段和一个value字段,如下所示:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// 创建一个新的自定义类型字典
var dict = new Dictionary<(string, string), int>();
// 添加一些键值对
dict.Add(("key1", "subkey1"), 1);
dict.Add(("key1", "subkey2"), 2);
dict.Add(("key2", "subkey1"), 3);
dict.Add(("key2", "subkey2"), 4);
// 获取字典中的值
Console.WriteLine(dict[("key1", "subkey1")]); // 输出 1
// 遍历字典
foreach (var pair in dict)
{
Console.WriteLine($"{pair.Key.Item1}, {pair.Key.Item2} = {pair.Value}");
}
}
}
// 自定义类型
public class CustomKey
{
public string Key1 { get; set; }
public string Key2 { get; set; }
}
// 自定义类型字典
public class CustomDictionary
{
private Dictionary<CustomKey, int> dictionary = new Dictionary<CustomKey, int>();
public void Add(string key1, string key2, int value)
{
dictionary.Add(new CustomKey { Key1 = key1, Key2 = key2 }, value);
}
public int GetValue(string key1, string key2)
{
return dictionary[new CustomKey { Key1 = key1, Key2 = key2 }];
}
}
```
上述代码中,我们使用元组(Tuple)作为自定义类型的键,也可以定义一个自定义类型`CustomKey`,并将其作为字典的键。当然,也可以像上述代码中那样,自定义一个包含两个key字段和一个value字段的类,然后使用这个类作为字典的键。这样就可以实现两个key对一个value的映射。