我会使用Dictionary<string, HashSet<string>> 将一个键映射到它的所有值。
这是一个完整的解决方案。首先,编写几个扩展方法来将 (key,value) 对添加到您的 Dictionary 和另一个以获取所有 (key,value) 对。请注意,我对键和值使用任意类型,您可以将其替换为 string 没有问题。
您甚至可以在其他地方编写这些方法而不是作为扩展,或者根本不使用方法,而只是在程序的某个地方使用此代码。
public static class Program
{
public static void Add<TKey, TValue>(
this Dictionary<TKey, HashSet<TValue>> data, TKey key, TValue value)
{
HashSet<TValue> values = null;
if (!data.TryGetValue(key, out values)) {
// first time using this key? create a new HashSet
values = new HashSet<TValue>();
data.Add(key, values);
}
values.Add(value);
}
public static IEnumerable<KeyValuePair<TKey, TValue>> KeyValuePairs<TKey, TValue>(
this Dictionary<TKey, HashSet<TValue>> data)
{
return data.SelectMany(k => k.Value,
(k, v) => new KeyValuePair<TKey, TValue>(k.Key, v));
}
}
现在你可以按如下方式使用它:
public static void Main(string[] args)
{
Dictionary<string, HashSet<string>> data = new Dictionary<string, HashSet<string>>();
data.Add("k1", "v1.1");
data.Add("k1", "v1.2");
data.Add("k1", "v1.1"); // already in, so nothing happens here
data.Add("k2", "v2.1");
foreach (var kv in data.KeyValuePairs())
Console.WriteLine(kv.Key + " : " + kv.Value);
}
哪个会打印这个:
k1 : v1.1
k1 : v1.2
k2 : v2.1
如果您的键映射到List<string>,那么您需要自己处理重复项。 HashSet<string> 已经为你做到了。