我有一个包含11个数字的数组,以及一个包含11个名字的数组。我还获得了平均值和前三个数字。数字和名称分别是用户输入,然后进入两个单独的数组。
例如,假设我有:
playerName[0] = player1.Text;
playerName[1] = player2.Text;
playerName[2] = player3.Text;
playerName[3] = player4.Text;
playerName[4] = player5.Text;
playerName[5] = player6.Text;
playerScore[0] = int.Parse(score1.Text);
playerScore[1] = int.Parse(score2.Text);
playerScore[2] = int.Parse(score3.Text);
playerScore[3] = int.Parse(score4.Text);
playerScore[4] = int.Parse(score5.Text);
playerScore[5] = int.Parse(score6.Text);
int highestScore = playerScore.Max();
double averageScore = playerScore.Average();
int largest = int.MinValue;
int second = int.MinValue;
int third = int.MinValue;
foreach (int i in playerScore)
{
if (i > largest)
{
third = second;
second = largest;
largest = i;
}
else if (i > second && i != largest)
second = i;
else if (i > third && i != second)
third = i;
}
有没有简单的方法列出这样的东西?
textbox.Text = highest score is: " + highestScore + " by " -INSERT RELEVENT playerName HERE-
我可以想到一些方法,但是它很可能会成为一个巨大的问题和开关
由于
答案 0 :(得分:2)
创建一个类来表示一个Player对象,另一个类继承自List以包含你的玩家。然后你可以做这样的事情:
public class Player
{
public string Name { get; set; }
public int Score { get; set; }
public Player(string name)
{
Name = name;
}
}
public class Players : List<Player>
{
public void SortByScore()
{
Sort((a, b) => a.Score.CompareTo(b.Score));
}
public void SortByName()
{
Sort((a, b) => a.Name.CompareTo(b.Name));
}
}
答案 1 :(得分:1)
不是使用并行数组,而是将得分和名称分组到一个新类中,并包含以下数组:
class Player
{
public string Name { get; set; }
public int Score { get; set; }
}
Player players[] = new Player[11];
players[0] = new Player(){ Name = player1.Text, Score = int.Parse( score1.Text ) };
然后你可以遍历每个玩家并保存得分最高的玩家,而不仅仅是得分:
Player highestScore = players[0];
foreach( Player p in players )
{
if( highestScore.Score < p.Score )
{
highestScore = p;
}
}
textBox.Text = "Highest Score is: " + highestScore.Score + " by " + highestScore.Name;
另请注意,您不对文本框数据进行验证,因此如果文本不是int,则程序将抛出异常并可能崩溃。
答案 2 :(得分:0)
这适用于您当前的设计:
int index = playerScore.ToList().IndexOf(playerScore.Max());
textbox.Text = string.Format("highest score is:{0} - by player: {1}",playerScore.Max(),playerName[index]);
但最好的方法应该是创建提供该信息的类,然后创建一个列表,其中每个元素都包含您需要的信息,如名称和分数。
答案 3 :(得分:0)
DO:将您的逻辑封装到一个负责跟踪Player
信息的类中:
public class Player
{
public string Name { get; set; }
public int Score { get; set; }
}
DON&#39; T:Inherit List<T>
为分数封装排序逻辑的最简单方法是使用扩展方法:
public static class PlayerExtensions
{
public static IEnumerable<Player> SortByScore(this IEnumerable<Player> players)
{
return players.OrderByDescending(p => p.Score);
}
}
但是,我认为抽象这个LINQ代码没什么价值。 IMO,你可以使用简单的List<Player>
,当你需要分数时,只需执行players.OrderByDescending(p => p.Score);