Setting a key / value pair

I created the list as a class property and want to set key / value pairs when defining the list. I originally used the structure, but realized that this was probably not an ideal solution, so I replaced it with a list. The problem is that I get an error with syntax.

Any ideas?

private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>[]
    {
            new KeyValuePair<String, String>("lsd",""),
            new KeyValuePair<String, String>("charset", "")
    };
+5
source share
6 answers

Maybe I missed something, but I would use a dictionary instead of the word So easy ....

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

and then use it in the following 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);
+9
source

Try the following:

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

[]. , . (,).

, Tuple :

pirvate List<Tuple<string, string>> formData = new List<Tuple<string, string>>()
{
    new Tuple<string, string>("lsd",""),
    new Tuple<string, string>("charset", "")
};
+2

Change the comma to the comma on the third line and remove the square brackets from the first line.

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

By the way, if you change it to a dictionary, you will be able to more easily find values ​​by their key.

0
source

remove []from ad

0
source
private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>()
    {
            new KeyValuePair<String, String>("lsd",""),
            new KeyValuePair<String, String>("charset", "")
    };
  • Why []after the constructor?
  • Items in the collection initializer must be separated by a comma: ,.
0
source

to try

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

All Articles