Does .Net provides generic form of NameValueCollection or an alternative to
Dictionary<string,List<T>>
?
Something like
Person john = new Person();
...
Person vick = new Person();
...
NameValueCollection<Person> stringToPerson = new NameValueCollection<Person>();
stringToPerson.Add("John",john)
stringToPerson.Add("Vick",vick)
Actually in my case am forced to rely on Dictionary<string,List<Peron>>
, is there any other alternative?
Regards, Jeez
There's no such thing built in to the BCL as far as I know. I would just write your own class which wraps a Dictionary<string, List<T>>
internally and exposes appropriate methods (e.g., Add
could add an element to the List<T>
for the given key).
For example:
class NameValueCollection<T>
{
Dictionary<string, List<T>> _dict = new Dictionary<string, List<T>>();
public void Add(string name, T value)
{
List<T> list;
if (!_dict.TryGetValue(name, out list))
{
_dict[name] = list = new List<T>();
}
list.Add(value);
}
// etc.
}
The closest alternative is probably the ILookup<TKey, TElement>
interface. At the moment, the only public type that implements it in the BCL is the immutable Lookup<TKey, TElement>
class, an instance of which can be created with the Enumerable.ToLookup
method. If you want a mutable type that implements the interface, you'll have to write one yourself; you can find an example implementation here.
In your case, you probably want an ILookup<string, Person>
.
Oh, I see what you want to do now. You want to be able to add to the Person collection without having to create a new List each time. Extension methods to the rescue!
public static void SafeAdd<TValue>(this IDictionary<TKey, ICollection<TValue>> dict, TKey key, TValue value)
{
HashSet<T> container;
if (!dict.TryGetValue(key, out container))
{
dict[key] = new HashSet<TValue>();
}
dict[key].Add(value);
}
Usage:
var names = new Dictionary<string, ICollection<Person>>();
names.SafeAdd("John", new Person("John"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With