public IEnumerable <Match> CreateMatches(League league) { Random rnd = new Random(); var matches = new List <Match>(); var teams = teamService.RetrieveLeagueTeams(league).ToArray(); Validations.ValidateCollectionZero(teams, "There are no teams in the league"); if (teams.Length % 2 != 0) { throw new ArgumentOutOfRangeException("There are odd teams in the league"); } Team[,] matrix = new Team[teams.Length / 2, 2]; var i = 0; for (int j = 0; j < 2; j++) { for (int t = 0; t < teams.Length / 2; t++) { matrix[t, j] = teams[i]; i++; } } int index = 0; var statiums = context.Stadiums.ToArray(); DateTime date1 = new DateTime(2019, 3, 1); for (int z = 0; z < teams.Length - 1; z++) { for (int j = 0; j < teams.Length / 2; j++) { var match = new Match { HomeTeam = matrix[j, 0], AwayTeam = matrix[j, 1], Stadium = statiums[index], League = league, Date = date1 }; index++; date1 = date1.AddDays(1); matches.Add(match); context.Matches.Add(match); } index = 0; RotateMatrix(matrix.GetLength(0), matrix.GetLength(1), matrix); } context.SaveChanges(); var newMatches = new List <Match>(); foreach (var match in matches) { var newMatch = new Match { HomeTeam = match.AwayTeam, AwayTeam = match.HomeTeam, Stadium = match.Stadium, League = league, Date = match.Date.AddDays(teams.Length + 1) }; newMatches.Add(newMatch); context.Matches.Add(newMatch); context.SaveChanges(); } matches.AddRange(newMatches); return(matches); }