c# - 是否可以对字典字符串键进行部分字符串匹配?

标签 c# dictionary containers

我有一个 Dictionary<string, List<int>>在我以下列方式使用的代码中:

Key           Values  
2011-07-15    1, 2, 3
2011-07-20    4, 5, 6
2010-02-11    7, 8, 9

我的代码需要能够查询与键中特定子字符串匹配的所有值。例如,如果我有子字符串 2011-07它应该返回值 {1, 2, 3, 4, 5, 6} . 11 的子串应该从 1-9 返回所有 ID .

任何人都可以推荐一种简洁的方法来实现这一目标吗?或者提供更好的数据结构来检索这些信息?

最佳答案

我会做一个扩展方法:

public static class DictionaryExt
{
    public static IEnumerable<T> PartialMatch<T>(this Dictionary<string, T> dictionary, string partialKey)
    {
        // This, or use a RegEx or whatever.
        IEnumerable<string> fullMatchingKeys = 
            dictionary.Keys.Where(currentKey => currentKey.Contains(partialKey));

        List<T> returnedValues = new List<T>();

        foreach (string currentKey in fullMatchingKeys)
        {
            returnedValues.Add(dictionary[currentKey]);
        }

        return returnedValues;
    }
}

向字典添加值的“成本”不会改变,但检索成本会更高,但前提是您知道要进行部分匹配。

顺便说一句,我相信您可以在单个 Lambda 表达式中转换它,但概念保持不变。

编辑:在您的示例中,此方法将返回 2 个值列表,但您可以更改它以合并列表。这是您可以执行的扩展方法:

public static IEnumerable<T> PartialMatch<T>(
    this Dictionary<string, IEnumerable<T>> dictionary,
    string partialKey)
{
    // This, or use a RegEx or whatever.
    IEnumerable<string> fullMatchingKeys = 
        dictionary.Keys.Where(currentKey => currentKey.Contains(partialKey));

    List<T> returnedValues = new List<T>();

    foreach (string currentKey in fullMatchingKeys)
    {
        returnedValues.AddRange(dictionary[currentKey]);
    }

    return returnedValues;
}

编辑 2:想想看,您还可以使其更通用。使用下一个扩展方法,它可以在任何字典上工作,只要你提供一个 comparer 来检查你所说的“部分匹配”是什么意思:

public static IEnumerable<TValue> PartialMatch<TKey, TValue>(
    this Dictionary<TKey, IEnumerable<TValue>> dictionary,
    TKey partialKey,
    Func<TKey, TKey, bool> comparer)
{
    // This, or use a RegEx or whatever.
    IEnumerable<TKey> fullMatchingKeys = 
        dictionary.Keys.Where(currentKey => comparer(partialKey, currentKey));

    List<TValue> returnedValues = new List<TValue>();

    foreach (TKey currentKey in fullMatchingKeys)
    {
        returnedValues.AddRange(dictionary[currentKey]);
    }

    return returnedValues;
}

关于c# - 是否可以对字典字符串键进行部分字符串匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7816398/

相关文章:

python - 如何调用可以是整数或函数的字典项?

html - 网站跨越整个页面,我不希望它

types - into_boxed_slice() 方法有什么用?

c# - 使用MvcSiteMapProvider 4实现Image Sitemap

c# - 使用 PrintDocument 打印表单

c# - 覆盖现有文件后应用程序未更新

c# - 生成带有格式的文档文本

c# - 最有效的 Dictionary<K,V>.ToString() 格式?

c++ - 如何判断某物是否是容器?

python - map() 函数获取输入