我有一个类似的问题,如此链接中所述,使用部分键从Dictionary
获取数据,我的键DataType
string
。
这就是我的字典的样子
Key Values
GUID1+GUID2+GUID3 1, 2, 3
GUID1+GUID2+GUID3 4, 5, 6
GUID1+GUID2+GUID3 7, 8, 9
但是提供的解决方案是使用带有 linq inDictionary
的扩展方法从Dictionary
获取数据。我只想使用TryGetValue
传递Regex
或通配符表达式从Dictionary
中提取数据。
更好的方法是有一个字典字典:
Dictionary<Tuple<Guid, Guid>, Dictionary<Guid, string>> dictionary;
然后使用扩展方法以简化使用它的代码:
public static bool TryGetValue<TKey1, TKey2, TKey3, TValue>(this Dictionary<Tuple<TKey1, TKey2>, Dictionary<TKey3, TValue>> dict, TKey1 key1, TKey2 key2, TKey3 key3, out TValue value)
{
if (dict.TryGetValue(new Tuple<TKey1, TKey2>(key1, key2), out var subDict) && subDict.TryGetValue(key3, out value))
{
return true;
}
value = default(TValue);
return false;
}
public static bool Add<TKey1, TKey2, TKey3, TValue>(this Dictionary<Tuple<TKey1, TKey2>, Dictionary<TKey3, TValue>> dict, TKey1 key1, TKey2 key2, TKey3 key3, TValue value)
{
var mainKey = new Tuple<TKey1, TKey2>(key1, key2);
if (!dict.TryGetValue(mainKey, out var subDict))
{
subDict = new Dictionary<TKey3, TValue>();
dict[mainKey] = subDict;
}
subDict.Add(key3, value);
}
因此,当您插入字典时,您可以使用如下所示的扩展方法:
dictionary.Add(g1, g2, g3, v1);
然后获取一个值:
if (dictionary.TryGetValue(g1, g2, g3, out v1))
{
}
当然,外字典的键取决于你。我只是用Tuple
来说明所有内容如何保持强类型。