Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Key/Value Pairs

Tags:

c#

I've created a List as a property of the class, and want to set the Key/Value pairs when defining the List. I was originally using a structure but realized it's probably not the ideal solution so I changed it to a List. The problem is I'm getting an error with the syntax.

Any ideas?

private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>[]
    {
            new KeyValuePair<String, String>("lsd",""),
            new KeyValuePair<String, String>("charset", "")
    };
like image 589
James Jeffery Avatar asked Feb 27 '13 10:02

James Jeffery


2 Answers

Probably I'm missing something, but I would have used a Dictionary instead of
So simple....

Dictionary<string, string>formData = new Dictionary<string, string>
{
    {"lsd", "first"},
    {"charset", "second"}
};    

and then use it in these ways:

foreach(KeyValuePair<string, string>k in formData)
{
    Console.WriteLine(k.Key);
    Console.WriteLine(k.Value);
}
....
if(formData.ContainsKey("lsd"))
    Console.WriteLine("lsd is already in");
....    
string v = formData["lsd"];
Console.WriteLine(v);
like image 148
Steve Avatar answered Sep 28 '22 10:09

Steve


Try this:

private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>
{
    new KeyValuePair<String, String>("lsd",""),
    new KeyValuePair<String, String>("charset", "")
};

You had an extra [] in your definition. You are not creating an array, so you don't need it. Also when initializing list with some values, the values should be separated by a comma (,).

In my opinion, a better approach would be to use Tuple class:

pirvate List<Tuple<string, string>> formData = new List<Tuple<string, string>>()
{
    new Tuple<string, string>("lsd",""),
    new Tuple<string, string>("charset", "")
};
like image 36
Mohammad Dehghan Avatar answered Sep 28 '22 12:09

Mohammad Dehghan