Friday, September 26, 2014

Code Puzzle: Translate word problem into a C# model and list variable

Objective:
I would like a list of named people and a collection of their games. I want each of the games in the collection to have a name, console associated with it, and optional release date. How would I make a model and a variable that includes this list of people and all of their games? How can I use C# and put this into a model and call a variable for the list?

You need 2 classes in the model. I would make one for the people and call it "Person" and I would also make one for their games called "Game". Since these are both in the model, I would label Model at the end to make it a better convention. (NOTE: Model here refers to Model in the MVC pattern.. nothing to do with an actual game model etc. Don't get confused!) We would have:
public class PersonModel
{

}

public class GameModel
{

}

Now we need each of the people to have a name and a list of games. The PersonModel will have the properties of Name and a list of games. The type of list for the GameModelList is of type GameModel.

public class PersonModel
{
    public string PersonName { get; set; }
    public list GameModelList { get; set; } 
}

public class GameModel
{

}

The GameModel will have its own properties of name, console associated with it, and optional release date. The release date must be of type DateTime? which is a nullable DateTime.

public class GameModel
{
    public string GameName { get; set;}
    public string ConsoleName { get; set; }
    public DateTime? ReleaseDate { get; set; } 
}

Now, put everything together! And see below for the variable needed to call the list of people with their names and collection of games..

Final Solution:

public class PersonModel
{
    public string PersonName { get; set; }
    public list GameModelList { get; set; } 
}

public class GameModel
{
    public string GameName { get; set;}
    public string ConsoleName { get; set; }
    public DateTime? ReleaseDate { get; set; } 
}
Now make a list of people:
var peopleList = new List();