TreeView. US States and Cities
I've got a list view and I have to populate it with states as the root nodes, and the cities as the child nodes. It's a tedious task.
I have a Dictionary<String,List<String>>
and doing it like this.
Dictionary<string, List<String>> locations = new Dictionary<string, List<String>>();
List<String> alabama = new List<String>();
alabama.add("city1");
alabama.add("city2");
alabama.add("city3");
....
locations.add("alabama",alabama);
....
Doing that for each state and city is getting开发者_如何学编程 annoying, and I just cant help but think there is an easier way.
Any thoughts?
Using collection initializer syntax and arrays instead of lists reduces the number of keystrokes a bit:
var locations = new Dictionary<string, string[]>
{
{ "alabama", new[] { "city1", "city2", "city3", ... } },
...
}
You would be a lot better off creating an xml file with your state/city info in it and reading through that to do your tree view population. That way you can write two foreach loops to do your code parsing your xml file.
You can embed the XML file as a resource to your project so that you don't leave it on the file system, and you can parse it using linq if you're feeling really lucky.
Dictionary<string, List<String>> locations = new Dictionary<string, List<String>>();
//read XML into business object here.
foreach(var state in xml.States)
{
List<String> lst = new List<String>();
foreach(var city in state.Cities)
{
lst.add(city);
}
locations.add(state, lst);
}
I huge benefit of doing it this way is you can update the list of states without a code change, only an XML file will change. Depending on the structure of your application, you could even pull this list down from a web service if it makes sense.
var locations = new Dictionary<string, List<string>>{
{ "Alabama", new List<string> {
"City 1", "City 2", "City 3"
} },
{ "Alaska", new List<string> {
"City 14", "City 15"
} }
};
精彩评论