如何对字符串和整数数组进行排序?

时间:2014-12-07 22:10:33

标签: c# arrays sorting

我需要一些帮助将分割数组排序为从最高到最低,同时将名称保持在分数旁边。我有点不确定如何这样做,因为阵列是分开的。

这是我到目前为止的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace proj09LEA
{
    class Program
    {
        static void Main(string[] args)
        {
            // declare and array of integers          
            string[] name = new string[5];
            int[] score = new int[5];

            Console.WriteLine("\nSaturday Coder's Bowling Team");
            Console.WriteLine("Enter in a name and score for each person on the team.");
            Console.WriteLine("For example, Mary 143. Just hit Enter when you are done.\n");

            // fill an array with user input
            for (int i = 0; i < score.Length; i++)
            {
                Console.WriteLine("Enter in a name and score: ");
                string line = Console.ReadLine();

                name[i] = line.Substring(0, line.IndexOf(' '));
                score[i] = int.Parse(line.Substring(line.IndexOf(' ') + 1));
            }

            Console.WriteLine("------------ Input Complete ------------\n");
            Console.WriteLine("Here are the scores for this game, from highest to lowest:\n");

            for (int i = 0; i < score.Length; i++)
            {
                if (score[i] >= 300)
                {
                    Console.WriteLine("{0}'s score was {1}*.", name[i], score[i]);
                }
                else
                {
                    Console.WriteLine("{0}'s score was {1}.", name[i], score[i]);
                }
            }

            dynamic swap;
            for (int i = 0; i < score.Length - 1; i++)
            {
                for (int j = i + 1; j < score.Length; j++)
                {
                    swap = score[i];
                    score[i] = score[j];
                    score[j] = swap;

                    swap = name[i];
                    name[i] = name[j];
                    name[j] = swap;
                }
            }

            AverageScore(score);

            Console.WriteLine("Press Enter to continue. . .");
            Console.ReadLine();
        }

        static void AverageScore(int[] score)
        {
            int sum = score.Sum();
            int average = sum / score.Length;
            Console.WriteLine("The average score for this game was {0:d}.\n", average);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

就个人而言,我会使用一个班级来代表玩家,这样你就可以将名字和分数保持在一起。类似的东西:

public class Player
{
    public string Name { get; set; }
    public int Score { get; set; }
}

然后,你可以得到像这样的高,低和平均值:

private static void Main(string[] args)
{
    // Of course this list could be generated from user input, and the scores
    // would start at 0, incrementing as play progressed. This is just for example.
    var players = new List<Player>
    {
        new Player {Name = "Abe", Score = 140},
        new Player {Name = "Bert", Score = 200},
        new Player {Name = "Charlie", Score = 150},
        new Player {Name = "Donald", Score = 300},
        new Player {Name = "Ernie", Score = 120},
    };

    var maxScore = players.Max(p => p.Score);
    var minScore = players.Min(p => p.Score);

    foreach (var player in players.Where(p => p.Score == maxScore))
    {
        // Note the inline check for a perfect score, which adds a '*' after it
        Console.WriteLine("Congratulations {0}, your score of {1}{2} was the highest.",
            player.Name, player.Score, maxScore == 300 ? "*" : "");
    }

    foreach (var player in players.Where(p => p.Score == minScore))
    {
        Console.WriteLine("{0}, your score of {1} was the lowest. " + 
            "Better get some practice.", player.Name, player.Score);
    }

    Console.WriteLine("The average score for this game was {0}.", 
        players.Average(p => p.Score));
}

如果你想按分数对球员名单进行排序,你可以这样做:

// This will sort the list by the score, with the highest score first
// Just for fun, it then sorts any ties by the player name
players = players.OrderByDescending(p => p.Score).ThenBy(p => p.Name).ToList();

Console.WriteLine("Here are all the players and their scores:");
players.ForEach(p => Console.WriteLine(" - {0}: {1}", p.Name, p.Score));

答案 1 :(得分:0)

尝试这样对数组进行排序

dynamic swap;
for (int i = 0; i < score.length - 1; i++)
    for(int j = i + 1; j < score.length; j++)
    {
        if (score[i] < score[j]) 
        {
             swap = score[i];
             score[i] = score[j];
             score[j] = swap;

             swap = name[i];
             name[i] = name[j];
             name[j] = swap;
        }
    }

并将其用于完美分数

for (int i = 0; i < score.Length; i++)
{
    if (score[i] >= 300) 
    {
        Console.WriteLine("{0}'s score was {1}*.", name[i], score[i]);
    }
    else
    {
        Console.WriteLine("{0}'s score was {1}.", name[i], score[i]);
    }
}

答案 2 :(得分:0)

我的回答有点不同。除非这是学校问题并且你的老师想要你自己编写类型,否则我会编写一个存储所有Score数据和实现IComparable的类,并使用List.Sort方法进行排序。然后我重写Class的ToString方法,以你想要的方式显示分数。

存储数据的类:

public class BowlingScore : IComparable<BowlingScore>
{
    private int _score = 0;

    public string Name { get; set; }

    public bool IsPerfectGame { get; protected set; }

    public int Score
    {
        get { return this._score; }

        set 
        { 
                this._score = value; 
                this.IsPerfectGame = value == 300; 
        }
    }

    public override string ToString()
    {
        if (this.IsPerfectGame)
        {
            return string.Format("{0}'s score was {1}*", this.Name, this.Score);
        }
        else
        {
            return string.Format("{0}'s score was {1}", this.Name, this.Score);

        }
    }

    public int CompareTo(BowlingScore other)
    {
        return this.Score.CompareTo(other.Score);
    }
}

填写BowlingScore列表的代码,从低到高排序并显示高,低和平均分数。请注意,您可以获得超过1的高分和低分。

        List<BowlingScore> scores = new List<BowlingScore>()
        {
            new BowlingScore() { Name = "Joe", Score = 278},
            new BowlingScore() { Name = "Pete", Score = 300},
            new BowlingScore() { Name = "Lisa", Score = 27},
            new BowlingScore() { Name = "Trevor", Score = 50},
            new BowlingScore() { Name = "Jim", Score = 78},
            new BowlingScore() { Name = "Bob", Score = 27},
            new BowlingScore() { Name = "Sally", Score = 50},
        };

        Console.WriteLine();
        Console.WriteLine("Here are the Scores:");

        scores.Sort();

        foreach (BowlingScore score in scores)
        {
            Console.WriteLine(score);
        }

        Console.WriteLine();
        HighScores(scores);

        Console.WriteLine();
        LowScores(scores);

        Console.WriteLine();
        Console.WriteLine(string.Format("Average score:{0}", scores.Average(f => f.Score)));

        Console.WriteLine();
        Console.WriteLine("Press any key...");
        Console.ReadKey();

    static void HighScores(List<BowlingScore> scores)
    {
        int highScore = scores.ElementAt(scores.Count - 1).Score;

        for(int index = scores.Count -1; index > 0; index--)
        {
            BowlingScore bowlingScore = scores.ElementAt(index);

            if (bowlingScore.Score == highScore)
            {
                Console.WriteLine(string.Format("High Score: {0} {1}", bowlingScore.Name, bowlingScore.Score));
            }
            else
            {
                break;
            }
        }
    }

    static void LowScores(List<BowlingScore> scores)
    {
        int lowScore = scores.ElementAt(0).Score;

        for (int index = 0; index < scores.Count; index++)
        {
            BowlingScore bowlingScore = scores.ElementAt(index);

            if (bowlingScore.Score == lowScore)
            {
                Console.WriteLine(string.Format("Low Score: {0} {1}", bowlingScore.Name, bowlingScore.Score));
            }
            else
            {
                break;
            }
        }
    }