Reputation: 2133
I'm looking to create a class that returns a constructed dictionary. I'm uncertain how I code my constructor to return the dictionary, how to initialize multiple string values that would pair with the key, and the only examples I've found are very rough drafts. Here's a rough example:
namespace MyApp.Helpers
{
public enum HouseSize
{
Big,
Medium,
Small
}
class Houses
{
public static Dictionary<HouseSize, string> _dictionaryOfHouses;
public static Dictionary<HouseSize, string> Houses
{
get
{
if (_dictionaryOfHouses == null)
LoadHouses();
return _dictionaryOfHouses;
}
}
}
private static void LoadHouses()
{
_dictionaryOfHouses = new Dictionary<HouseSize, string>;
_dictionaryOfHouses.Add(HouseSize.Big, /*Add String Properties Here like Red, 2 Floor, Built in 1975*/);
_dictionaryOfHouses.Add(HouseSize.Small, /*Add String Properties Here like Blue, 1 Floor, Built in 1980*/);
}
}
Upvotes: 0
Views: 1273
Reputation: 4002
Using the existing enumeration for house sizes:
public enum HouseSize {
Big,
Medium,
Small
}
Create a class to describe a House's properties
public class HouseProperties {
public string Colour { get; set; }
public int NumFloors { get; set; }
public int Year { get; set; }
}
// Create a Dictionary of House Sizes
// Use a List<HouseProperties> so you can have multiple houses
// of a house size, that can even have the same colour, number
// of floors and/or year
Dictionary<HouseSize, List<HouseProperties>> HouseDictionary = new Dictionary<HouseSize, List<HouseProperties>>();
// Initialize the House sizes
HouseDictionary.Add(HouseSize.Big, new List<HouseProperties>());
HouseDictionary.Add(HouseSize.Medium, new List<HouseProperties>());
HouseDictionary.Add(HouseSize.Small, new List<HouseProperties>());
// Adding a 2013 one-floor Mahogany Big House to the Dictionary
HouseDictionary[HouseSize.Big].Add(new HouseProperties() {
Colour = "Mahogany",
NumFloors = 1,
Year = 2013
});
Upvotes: 0
Reputation: 20320
A couple of things first returning Dictionary
can be an issue, IDictionary
would be better.
I'd Look at something like
private static void LoadHouses()
{
_dictionaryOfHouses = new Dictionary<HouseSize, Dictionary<string,string>;
houseProperties = new Dictionary<String,String>();
houseProperties.Add("Colour", "Red");
// etc
_dictionaryOfHouses.Add(HouseSize.Big, houseProperties);
}
If you are feeling brave Dictionary>
now you can type your additional properties
so year built could be an int and Colour and enum..
After its' built then you can access it
with
Houses[HouseSize.medium]["Colour"]
Upvotes: 0
Reputation: 1653
You could use a List<string>
rather then a simple string
. Or perhaps another class that holds the properties such as:
class HouseProperties {
public string Color { get; set; }
public string YearBuilt { get; set; } // I assume having these as strings is more
public string NumFloors { get; set; } // helpful then storing the number itself
}
Upvotes: 1