Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic form of NameValueCollection in .Net

Tags:

c#

.net

generics

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

like image 660
Jeevan Avatar asked Mar 06 '11 08:03

Jeevan


3 Answers

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.
}
like image 171
Dan Tao Avatar answered Oct 03 '22 16:10

Dan Tao


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>.

like image 30
Ani Avatar answered Oct 03 '22 15:10

Ani


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"));
like image 27
Josh Smeaton Avatar answered Oct 03 '22 15:10

Josh Smeaton