Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a pair of strings in a non-unique list

Tags:

c#

.net

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

like image 317
Chris Avatar asked Aug 19 '11 10:08

Chris


People also ask

What is used to store a list of strings?

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.

Can KeyValuePair have duplicate keys?

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


1 Answers

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;
}
like image 86
Daniel Hilgarth Avatar answered Nov 16 '22 23:11

Daniel Hilgarth