Elmo
Elmo

Reputation: 6471

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?

Upvotes: 7

Views: 18863

Answers (3)

Yusubov
Yusubov

Reputation: 5843

In short: The easiest way to go would be a generic List<T> collection while skiping the ArrayList class. Because, there are some performance considerations that you need to take into account.

In addition, you can also use List<KeyValuePair<string,int>>. This will store a list of KeyValuePair 's that can be duplicate.

In deciding whether to use the List<T> or ArrayList class, both of which have similar functionality, remember that the List<T> class performs better in most cases and is type safe. If a reference type is used for type T of the List<T> class, the behavior of the two classes is identical. However, if a value type is used for type T, you need to consider implementation and boxing issues.

As reference: you may use the following MSDN article - List Class.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564441

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);
}

Upvotes: 12

Dave Zych
Dave Zych

Reputation: 21887

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" });

Upvotes: 6

Related Questions