2016-12-22 6 views
0
public class Player 
{ 
    public string Name { get; private set; } 
    public string Firstname { get; private set; } 
    public Ploeg Team { get; private set; } 
    public int Goal { get; set; } 
} 
public class GlobalCollection 
{ 
    public List<Ploeg> PloegCollection { get; private set; } 
    public List<Speler> SpelerCollection { get; private set; } 
} 
public GlobalCollection() 
{ 
     SpelerCollection.Add(new Speler("Stanciu", "Nicolae", p1 , 0)); 
     SpelerCollection.Add(new Speler("Massimo", "Bruno", p1 , 0)); 
     SpelerCollection.Add(new Speler("Hanni", "Sofiane", p1 , 0)); 
     SpelerCollection.Add(new Speler("Teodorczyk", "Lukasz", p1, 0)); 
} 

У меня есть кнопка, которая задает цели +1.Попытка получить самый высокий голевой счет в списке игроков, голы

private void goalButton_Click(object sender, EventArgs e) 
    { 
     if (ploeg1ListBox.SelectedIndex >= 1) 
     { 
      Player pl = (Player)team1ListBox.SelectedItem; 
      pl.player++; 
      GoalForm goal = new GoalForm(); //winform with picture 
      goal.ShowDialog(); 
     } 

Теперь я хочу показать нажатием одной кнопки самый высокий бомбардир. Я попытался с помощью MAXVALUE и так далее ..

foreach(Speler sp in data.SpelerCollection) 
    { 
     for (int counter = 0; counter > data.SpelerCollection.Count;counter++) 
     { 

я не могу показаться, чтобы найти правильный код для моей маленькой программы, могли бы вы помочь мне, ребята?

ГРЦ

+1

Если у вас есть Linq вы можете использовать 'Max', чтобы получить наибольшее количество баллов игрока. – nbokmans

ответ

4

Почему нет:

var maxGoals = SpelerCollection.Max(s => s.Goal); 
Speler maxScorer = SpelerCollection.Where(s => s.Goal == maxGoals).First(); 
// rest of your logic ... 
// you should handle the case, when more than one 
// player have scored the same amount of goals. 
// It would be better to get a collection back and then 
// display the result depending on the number of players returned 
+1

Собирался прокомментировать, что Одиночка, вероятно, не к лучшему. Я просто оставлю это, чтобы вернуть 'IEnumerable ' для самых высоких или совместных наивысших баллов. – Chris

+0

@Chris Вы правы, но он попросил один объект. Но op может легко изменить ответ на коллекцию. – Mithrandir

+1

Я все равно предпочитаю '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ''' '' '' '' '' '' '' '' '' '' '' '' ''' '' '' '' '' '' '' '' '' '' '' '' '' '' за исключения. :) – Chris

6

Один из способов сделать это:

var playerWithHighestGoalRank = data.SpelerCollection 
             .OrderByDescending(player => player.Goal) 
             .First(); 
Смежные вопросы