How to give Hardcoded values to Dictionary
This is my Dictionary.
Dictionary<string, Test> test = new Dictionary<string, Test>();
In the Test, i am having Id,Name,Score. I want to fill these properties with hard coded values.(More than one count).
How to give static values to Dictionary
Whether i should give like this...
Dictionary<string, Test> test= new Dictionary<string, Test>();
Groups groups = new Groups();
groups.Id = "1";
groups.Name = "Name";
groups.Description = "Desc";
test.Add(groups.Id, g开发者_Go百科roups);
You can use the collection initialiser syntax in C#3 & 4:
var data = new Dictionary<String,Object> {
{ "Foo", "Bax" },
{ "Bar", new DateTime(2010,10,10) },
{ "Xyzzy", 42 }
};
Additional: The updated question code:
Dictionary<string, Test> test= new Dictionary<string, Test>();
Groups groups = new Groups();
groups.Id = "1";
groups.Name = "Name";
groups.Description = "Desc";
test.Add(groups.Id, groups);
can be re-written as a single expression (also noting the value type seems to be Groups
, and showing how to add multiple key-value pairs):
Dictionary<string, Test> test= new Dictionary<string, Groups> {
{
"1", new Groups {
Id = "1",
Name = "Name",
Description = "Desc"
}
}, {
"2", new Groups {
Id = "2",
Name = "Another Name",
Description = "Something }
}
};
精彩评论