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

本文关键字:数组 排序 整数 字符串 | 更新日期: 2023-09-27 18:33:23

我需要一点帮助,将拆分数组从高到低排序,同时将名称保留在分数旁边。我有点不确定该怎么做,因为数组是分开的。

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

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);
        }
    }
}

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

就我个人而言,我会用一个类来代表球员,这样你就可以把名字和分数放在一起。像这样:

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));

尝试对数组进行排序

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]);
    }
}

我的回答有点不同。 除非这是学校的问题,并且您的老师希望您编写自己的排序,否则我会编写一个存储所有分数数据并实现 IComparable 的类,并使用 List.Sort 方法进行排序。 然后,我重写了类的 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);
    }
}

用于填充保龄球分数列表的代码,从低到高排序,并显示高、低和平均分数。 请注意,您可以有超过 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;
            }
        }
    }