Sunday, February 28, 2016

May I cast a dictionary to a list in C#?

Not exactly, no. The following is as close as one may get. This test passes:

[TestMethod]
public void may_cast_dictionary_to_list()
{
   
//arange
   Dictionary<string, string> deepSouthCapitals = new Dictionary<string, string>();
   deepSouthCapitals["Alabama"] = "Montgomery";
   deepSouthCapitals["Georgia"] = "Atlanta";
   deepSouthCapitals["Louisiana"] = "Baton Rouge";
   deepSouthCapitals["Mississippi"] = "Jackson";
   deepSouthCapitals["South Carolina"] = "Columbia";
   
   
//act
   List<string> states = deepSouthCapitals.Keys.ToList();
   List<string> cities = deepSouthCapitals.Values.OrderBy(x => x).ToList();
   
   
//assert
   Assert.AreEqual(states.Count, 5);
   Assert.AreEqual(states[0], "Alabama");
   Assert.AreEqual(states[1], "Georgia");
   Assert.AreEqual(states[2], "Louisiana");
   Assert.AreEqual(states[3], "Mississippi");
   Assert.AreEqual(states[4], "South Carolina");
   Assert.AreEqual(cities.Count, 5);
   Assert.AreEqual(cities[0], "Atlanta");
   Assert.AreEqual(cities[1], "Baton Rouge");
   Assert.AreEqual(cities[2], "Columbia");
   Assert.AreEqual(cities[3], "Jackson");
   Assert.AreEqual(cities[4], "Montgomery");
}

No comments:

Post a Comment