首页 > 解决方案 > 在 C# 中,对两个或多个不同数据类型的数组进行排序的最佳方法是什么?Array.Sort 似乎一次只有一种数据类型

问题描述

我可以使用单个数据类型(例如字符串)对数组进行排序,但是如何对具有不同数据类型的其他数组进行排序并按照相同字符串数据类型的升序排列?

如您所见Array.Sort,我在代码底部附近有一种方法,其中playerNameplayerPosition数组正在排序。我想添加 int[] 数组atBatshits. 然后我需要添加击球平均值,它也是一个浮点值。

using System;
using static System.Console;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//My Baseball application named BatStat
namespace BatStat
{
    class Program
    {
        static void Main()
        {
            //My declared variables that hold the user input in memory
            string teamName;
            string[] playerName = new string[3];
            string[] playerPosition = new string[3];
            int[] atBats = new int[3];
            int[] hits = new int[3];


            //Begin program by requesting user to enter team name value
            WriteLine("Welcome to Bat Stat, enter team name");
            teamName = Console.ReadLine();

            //Traverse all arrays and accumalate values from user input
            for (int i = 0; i < playerName.Length; i++)
            {
                WriteLine("Enter players name");
                playerName[i] = ReadLine();
                WriteLine("Enter Players Position");
                playerPosition[i] = ReadLine();
                WriteLine("Enter Players at bats");
                atBats[i] = Convert.ToInt32(ReadLine());
                WriteLine("Enter Players hits");
                hits[i] = Convert.ToInt32(ReadLine());
            }

            //Display top row menu for Bat Stat table
            WriteLine("{0, -10}{1, -10}{2, -5}{3, -5}{4, -5}{5, -5}", "Team", "Player", "Pos", "AB", "H", "BA");

            //for loop to traverse the arrays and display user input data in tabular format
            for (int x = 0; x < playerName.Length; ++x)
            {
                Array.Sort(playerName, playerPosition);
                float playerBA = (float)hits[x] / atBats[x];
                WriteLine("{0, -10}{1, -10}{2, -5}{3, -5}{4, -5}{5, -4}", teamName, playerName[x], playerPosition[x], atBats[x].ToString("d"), hits[x].ToString("d"), playerBA.ToString("F3"));
            }

            //Display the team batting average at bottom in a single row
            float teamBA = (float)hits.Sum() / atBats.Sum();
            WriteLine("The batting average for the {0} is {1}", teamName, teamBA.ToString("F3"));

        }
    }
}

标签: c#arraystypesint

解决方案


由于您使用 C#(一种面向对象的语言)进行编码,因此您应该考虑使用对象。你可以为 Player 声明你自己的类,保存你每次输入的信息。

然后,当您按球员姓名和位置排序时,所有字段都会排序,因为您将他们之间的所有球员作为一个整体进行排序,而不是特定字段。

您可以将您的班级定义为:

public class Player
{
    public string Name { get; set; }
    public string Position { get; set; }
    public int AtBats { get; set; }
    public int Hits { get; set; }
}

您可以摆脱多个数组,并使用: Player[] players = new Player[3];

在你的循环中,你可以像这样创建玩家:

for (int i = 0; i < players.Length; i++)
{
    var player = new Player();
    WriteLine("Enter players name");
    player.Name = ReadLine();
    WriteLine("Enter Players Position");
    player.Position = ReadLine();
    WriteLine("Enter Players at bats");
    player.AtBats = Convert.ToInt32(ReadLine());
    WriteLine("Enter Players hits");
    player.Hits = Convert.ToInt32(ReadLine());

    players[i] = player;
}

希望能把事情弄清楚一点,让你开始。

至于比较本身,您有多种方法可以做到这一点。如果要使用 Array 而不是 List,最直接的方法是Player实现IComparable接口。这样每个 Player 对象都知道如何将自己与另一个玩家进行比较。

如果我理解正确,您想先按名称排序,然后按位置排序?然后您可以将 Player 类修改为:

public class Player : IComparable
{
    public string Name { get; set; }
    public string Position { get; set; }
    public int AtBats { get; set; }
    public int Hits { get; set; }

    public int CompareTo(object obj)
    {
        if (obj == null) return 1;
        var otherPlayer = obj as Player;
        int result = this.Name.CompareTo(otherPlayer.Name);
        if (result == 0) 
        {
            result = this.Position.CompareTo(otherPlayer.Position);
        }
        return result;
    }
}

然后,对玩家进行排序将是一个简单的调用:Array.Sort(players);程序的第二个循环变为:

//for loop to traverse the arrays and display user input data in tabular format
Array.Sort(players);
for (int x = 0; x < players.Length; x++)
{
    var player = players[i];
    float playerBA = (float)player.Hits / player.AtBats;
    WriteLine("{0, -10}{1, -10}{2, -5}{3, -5}{4, -5}{5, -4}", teamName, player.Name, player.Position, player.AtBats, player.Hits, playerBA.ToString("F3"));
}

请注意:您对数组进行了 3 次排序,但您只需要一次。在这里你有 3 个元素并没有什么不同,但如果你有更多的元素,它会花费你。

您也不需要.ToString("d"),因为它是整数的默认值,并且.ToString()在您调用 WriteLine 时会自动进行转换。


推荐阅读