【问题标题】:Regex or wildcard in dictionary.TryGetValue字典中的正则表达式或通配符。TryGetValue
【发布时间】:2018-06-29 07:10:43
【问题描述】:

我有类似Link 中提到的问题,使用部分密钥从Dictionary 获取数据,而我的密钥DataType 是string。

这就是我的字典的样子

Key                                   Values  
GUID1+GUID2+GUID3                     1, 2, 3
GUID1+GUID2+GUID3                     4, 5, 6
GUID1+GUID2+GUID3                     7, 8, 9

但提供的解决方案是使用Dictionary 中的linq 扩展方法从Dictionary 获取数据。我只想使用TryGetValue 传递Regex 或通配符表达式从Dictionary 中提取数据。

【问题讨论】:

  • 请注意,这样做会失去字典提供的任何性能提升。原因是字典首先找到与键的哈希码匹配的项目,然后对每个项目键执行相等比较以找到完全匹配的项目。如果您使用任何类型的部分/通配符方法,这是不可能的,因此您不妨使用.Where(kv => regex.IsMatch(kv.Key)) 之类的东西来获得具有所有匹配结果的IEnumerable。
  • 我不确定这是否正确,但是否可以创建一个像 Dictionary<Regex, MyClass> myDictionary new Dictionary<Regex, MyClass>() 这样的 Dictionary 并在 myDictionary.TryGetValue("some regex", out myData) 中使用正则表达式获取,这会对性能产生任何影响。
  • 我提到了它,但是那里提供的解决方案是使用扩展方法,但我想在不影响性能的情况下使用Dictionary 中的TryGetValue 方法获取数据。我在我的问题@Sinatr 中提到了这一点
  • 听起来你想要一本字典,其中外部的有GUID+GUID2 作为键,而内部的有GUID3。

标签: c# .net dictionary


【解决方案1】:

一个更好的方法是拥有一本字典:

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 来说明一切如何保持强类型化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多