Lookup extension method
Rather than create a whole new class implementing ILookup<T>
is it possible to add an extension method to dictionary which caters for it? I'm thinking something along the following:
public static void LookupAdd(this Dictionary<T, List<V>> dict, T key, V item)
{
if (!dict.ContainsKey(key))
{
dict.Add(key, new List<T>());
}
dict[key].Add(item);
}
This fails to compile saying it can't identify the types. I'm guessing that my generic parameters are too co开发者_StackOverflow社区mplex (particularly List<V>
)
You have forgotten to add the generic parameter syntax:
public static void LookupAdd<T, V>(this Dictionary<T, List<V>> dictionary, T key, V item)
{
}
The <T, V>
is missing.
Try...
public static void LookupAdd<T,V>(this Dictionary<T, List<V>> dict, T key, V item)
{
if (!dict.ContainsKey(key))
{
dict.Add(key, new List<V>());
}
dict[key].Add(item);
}
UPDATE:
Notice that you should have
new List<V>()
where you have
new List<T>()
精彩评论