Working with Enums

Next item that we want to get is team name. So, we just added another constructor for team name in GameResult class.

public String TeamName { get; set; }

And in our Main class, inside while loop in ReadFootballResults.

GameResult.TeamName = values[1];

It is done. Next, we look at the adjacent column, Home or Away column.

Due to only 2 values, home or away. We could write our own Enumerator. Get back to GameResult class.

// inside GameResult class
public HomeOrAway HomeOrAway { get; set; }

// below GameResult class
public enum HomeOrAway
{
    Home,
    Away
}

Now, we called it on Main class.

HomeOrAway HomeOrAway;
if (Enum.TryParse(values[2], out HomeOrAway))
{
    GameResult.HomeOrAway = HomeOrAway;
}

After that, we could change our List of string into List of GameResult.

public static List<GameResult> ReadFootballResults(string fileName)
{
    var soccerResults = new List<GameResult>();
    using (var reader = new StreamReader(fileName))
    {
        var line = "";
        reader.ReadLine();
        while ((line = reader.ReadLine()) != null)
        {
            var GameResult = new GameResult();
            DateTime gameDate;
            string[] values = line.Split(',');

            if (DateTime.TryParse(values[0], out gameDate))
            {
                GameResult.GameDate = gameDate;
            }
            GameResult.TeamName = values[1];

            HomeOrAway HomeOrAway;
            if (Enum.TryParse(values[2], out HomeOrAway))
            {
                GameResult.HomeOrAway = HomeOrAway;
            }
            soccerResults.Add(GameResult);
        }
    }
    return soccerResults;
}

results matching ""

    No results matching ""