I've got a situation where I am loading some config data from an XML document and I have a bunch of elements that contain pairs of strings. I am tryign to look for a good way of storing these in a single object.
I'm after something like Dictionary<string,string>
except that I want to be able to have duplicate keys and I will never be searching it for a single value, jsut iterating through it to generate some HTML to put on a page.
Is there a good object to use? I know I could create a little class of my own to hold the two bits of data and have a List of them but that seems a bit excessive.
I could also just have two Lists and just know that the nth element in one goes with the nth element in the other. This strikes me as a recipe for disaster of some kind though.
There is also System.Web.UI.Pair that seems to do what I want but I'm not sure if its good practice to use that given its in the System.Web.UI namespace...
I'm probably missing something obvious but I thought I'd ask rather than spending any more of my time trying to think about the best way to do this. :)
List(Of String) is a perfectly good way of storing a list of strings. If you need to add/remove elements from in the middle, you might want to consider using a LinkedList(Of String) but for most situations List is fine.
You can use List<KeyValuePair<string,int>> . This will store a list of KeyValuePair 's that can be duplicate.
You can simply use a List<KeyValuePair<string, string>>
or a List<Tuple<string, string>>
.
You would add items like this:
// for List<KeyValuePair<string, string>>
list.Add(new KeyValuePair<string, string>(value1, value2));
// for List<Tuple<string, string>>
list.Add(Tuple.Create(value1, value2));
You can access the items like this:
foreach(var item in list)
{
// for List<KeyValuePair<string, string>>
var value1 = item.Key;
var value2 = item.Value;
// for List<Tuple<string, string>>
var value1 = item.Item1;
var value2 = item.Item2;
}
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