Reputation: 557
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", "")
};
Upvotes: 5
Views: 37059
Reputation: 216293
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);
Upvotes: 13
Reputation: 18443
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", "")
};
Upvotes: 3
Reputation: 709
try
private List<KeyValuePair<String, String>> formData = new List<KeyValuePair<String, String>>
{
new KeyValuePair<String, String>("lsd",""),
new KeyValuePair<String, String>("charset", "")
};
Upvotes: 0
Reputation: 125630
private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>()
{
new KeyValuePair<String, String>("lsd",""),
new KeyValuePair<String, String>("charset", "")
};
[]
after the constructor?,
.Upvotes: 0
Reputation: 19175
Change the semi-colon to a 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", "")
};
Incidentally, if you change it to a Dictionary you get the ability to look up the values by their key more easily.
Upvotes: 0