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