问题描述
我的代码中有一个 Dictionary<string, List<int>>
,我使用以下方式:
I have a Dictionary<string, List<int>>
in my code which I am using in the following manner:
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.
My code needs to be able to query for all values matching a particular substring in the key. For example, if I had the substring 2011-07
it should return values {1, 2, 3, 4, 5, 6}
. A substring of 11
should return all IDs from 1-9
.
谁能推荐一种简洁的方法来实现这一点?或者提供更好的数据结构来检索这些信息?
Can anyone recommend a concise way to achieve this? Or provide a better data structure for retrieving this information?
推荐答案
我会做一个扩展方法:
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;
}
}
向字典添加值的成本"不会改变,但检索成本会更高,但前提是您知道要进行部分匹配.
The "cost" of adding values to the dictionary wouldn't change, but the cost of retrieval would be higher, but only when you know you're going with a partial match.
顺便说一句,我相信您可以将其转换为单个 Lambda 表达式,但概念保持不变.
Btw, I'm sure you could transform this in a single Lambda expression, but the concept remains the same.
编辑:在您的示例中,此方法将返回 2 个值列表,但您可以更改它以合并列表.这是您可以做的扩展方法:
Edit: In your example, this method would return 2 lists of values, but you can change it to merge the lists. Here is the extension method you could do :
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
来检查部分匹配"的含义:
Edit 2: Come to think of it, you could also make it more generic. With the next extension method, it would work on any dictionary, as long as you provide a comparer
that check what you mean by "partial match" :
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;
}
这篇关于是否可以对 Dictionary 字符串键进行部分字符串匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!