Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Collection which allows same key

Collections like HashTable and Dictionary don't allow to add a value with the same key but I want to store the same values with the same keys in a Collection<int,string>.

Is there a built-in collection which lets me do this?

like image 592
Elmo Avatar asked Jan 03 '13 20:01

Elmo


2 Answers

You can use a List<T> containing a custom class, or even a List<Tuple<int,string>>.

List<Tuple<int,string>> values = new List<Tuple<int,string>>();

values.Add(Tuple.Create(23, "Foo"));
values.Add(Tuple.Create(23, "Bar"));

Alternatively, you can make a Dictionary<int, List<string>> (or some other collection of string), and populate the values in that way.

Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();
dict.Add(23, new List<string> { "Foo", "Bar" });

This has the advantage of still providing fast lookups by key, while allowing multiple values per key. However, it's a bit trickier to add values later. If using this, I'd encapsulate the adding of values in a method, ie:

void Add(int key, string value)
{
    List<string> values;
    if (!dict.TryGetValue(key, out values))
    {
        values = new List<string>();
        dict[key] = values;
    }

    values.Add(value);
}
like image 94
Reed Copsey Avatar answered Sep 27 '22 21:09

Reed Copsey


Use a List with a custom Class.

public class MyClass
{
    public int MyInt { get; set; }
    public string MyString { get; set; }
}

List<MyClass> myList = new List<MyClass>();
myList.Add(new MyClass { MyInt = 1, MyString = "string" });
like image 22
Dave Zych Avatar answered Sep 27 '22 21:09

Dave Zych