Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best collection type to easily lookup values with multiple, identical keys?

I have text documents like the following which contain single and multiple variables:

title:: Report #3
description:: This is the description.
note:: more information is available from marketing
note:: time limit for this project is 18 hours
todo:: expand the outline
todo:: work on the introduction
todo:: lookup footnotes

I need to iterate through the lines of this text document and fill a collection with these variables, currently I'm using a Dictionary:

public Dictionary<string, string> VariableNamesAndValues { get; set; }

But this doesn't work on multiple, identical keys such as "note" and "todo" in the above example since keys have to be unique in a Dictionary.

What is the best collection so that I can not only get single values like this:

string variableValue = "";
if (VariableNamesAndValues.TryGetValue("title", out variableValue))
    return variableValue;
else
    return "";

but that I can also get multiple values out like this:

//PSEUDO-CODE:
List<string> variableValues = new List<string>();
if (VariableNamesAndValues.TryGetValues("note", out variableValues))
    return variableValues;
else
    return null;
like image 213
Edward Tanguay Avatar asked Mar 06 '10 18:03

Edward Tanguay


1 Answers

If your keys and values are strings then use a NameValueCollection. It supports multiple values for a given key.

It's not the most efficient collection in the world. Particularly because it's a non-generic class, uses a lot of virtual method calls, and the GetValues method will allocate arrays for its return values. But unless you require the best performing collection, this is certainly the most convenient collection that does what you ask.

like image 134
Josh Avatar answered Jan 02 '23 16:01

Josh