Reputation: 29
I'm trying to create an application that randomizes a list of teams and then display the matchups. As you can see from the picture everything works except the matchups are suppose to be on the same row. I do know the cause of this but I'm not sure how to properly fix it(If possible). Also, I apologize for the title - I didn't know what to call it.
I believe the cause is when I'm adding to the MatchUp ObservableCollection I am not putting both Team1 and Team2 into the Add function, which means it's left blank?
void GetRandomMatchUps()
{
randomNums.Clear();
MatchUp.Clear();
Random random = new Random(DateTime.Now.Millisecond);
int randomPick;
bool completed = false;
int count = 0;
while(!completed)
{
randomPick = random.Next(0, team.Count);
if (!randomNums.Contains(randomPick))
{
randomNums.Add(randomPick);
count++;
if(count % 2 == 0)
MatchUp.Add(new Round() { Team1 = team[randomPick].Name });
else
MatchUp.Add(new Round() { Team2 = team[randomPick].Name });
}
else if(randomNums.Count == team.Count)
{
completed = true;
}
}
}
XAML
<ListBox Grid.RowSpan="2" Grid.Column="0" Margin="10" Height="200" Name="matchList">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="180"/>
<ColumnDefinition Width="180"/>
<ColumnDefinition Width="180"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Team1}" Grid.Column="0" HorizontalAlignment="Center"/>
<TextBlock Text="VS" Grid.Column="1" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding Team2}" Grid.Column="2" HorizontalAlignment="Center"/>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
CLASS
class Round
{
public string Team1 { get; set; }
public string Team2 { get; set; }
}
Upvotes: 0
Views: 52
Reputation: 128096
This simple method creates a collection of random matches:
public static IEnumerable<Round> CreateRandomMatches(List<Team> teams)
{
var random = new Random();
var randomTeams = teams.OrderBy(t => random.Next()).ToList();
for (int i = 1; i < teams.Count; i += 2)
{
yield return new Round
{
Team1 = randomTeams[i - 1].Name,
Team2 = randomTeams[i].Name
};
}
}
Upvotes: 1