如何将一个数组拆分为两个不同的数组

本文关键字:数组 两个 一个 拆分 | 更新日期: 2023-09-27 18:32:15

我似乎无法弄清楚如何修复我的代码以使其正常工作。我需要用户能够输入他们的名字,然后输入空格,然后输入他们的得分。然后我需要将数组拆分为两个不同的数组,并将它们传递给四种不同的方法,以向用户显示他们的得分等。谁能帮我解决这个问题?

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
            int[] array = new int[10];
            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 < array.Length; i++)
            {
                Console.WriteLine("Enter in a name and score: ");
                string userInput;
                string[] parsedInput;
                parsedInput = userInput.Split();
                string name = parsedInput[0];
                int score = int.Parse(parsedInput[1]);
            }
            Console.WriteLine("------------ Input Complete ------------'n");
            Console.WriteLine("Here are the scores for this game:");
            DisplayScore(array);
            HighScore(array);
            LowScore(array);
            AverageScore(array);
            Console.WriteLine("Press Enter to continue. . .");
            Console.ReadLine();
        }
        static void DisplayScore(int[] array)
        {
            foreach (int n in array)
            {
                Console.WriteLine("{0}'s score was {0}.'n", array);
            }
        }
        static void HighScore(int[] array)
        {
            int max = array.Max();
            Console.WriteLine("Congratulations {0}, your score of {0} was the highest.", max);
        }
        static void LowScore(int[] array)
        {
            int min = array.Min();
            Console.WriteLine("{0}, your score of {0} was the lowest. Better get some practice.", min);
        }
        static void AverageScore(int[] array)
        {
            int sum = array.Sum();
            int average = sum / array.Length;
            Console.WriteLine("The average score for this game was {0:d}.", average);
        }
    }
}

如何将一个数组拆分为两个不同的数组

如果你绝对必须使用简单的基元数组,你需要两个大小相同的不同数组,将名称保存为字符串,将分数保存为整数:

class Program
{
    const int MaxScores = 10;  // .. Use a constant to ensure the sizes remain in sync
    static void Main(string[] args)
    { ///
        string[] names = new int[MaxScores];
        int[] scores = new int[MaxScores];
        // ... parse names into names[] and scores into scores[]
        DisplayScore(names, scores);

然后,您需要将两个数组传递给各种方法:

static void DisplayScore(string[] names, int[] scores)
{
   for(int i=0; i < MaxScores; i++)
   {
       Console.WriteLine("{0}'s score was {1}.'n", names[i], scores[i]);
   }
}
// etc

但是,有更好的方法可以做到这一点,例如通过为Name, Score元组定义一个自定义类:

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

然后,您可以声明并传递单个PersonScore[]数组。

PersonScore[] personScores = new PersonScore[MaxScores];
for (... prompting the user for data) 
{
   ... parsing user input
   personScores[i] = new PersonScore{Name = name, Score = score};
}
DisplayScore(personScores); // Pass around the single array
static void DisplayScore(IEnumerable personScores)
{
   foreach(var personScore in personScores)
   {
       Console.WriteLine("{0}'s score was {1}.'n", personScore.Name, personScores.Score);
   }
}
// etc - other methods

正如其他人所提到的,其他集合也是数组的可能替代品,最常见的是List

你可以

这样做。只需使用 Console.ReadLine() 获取用户输入。这就是您在代码中执行的操作。有更好的方法可以做到这一点,但以下将解决您的问题。您还需要执行验证。

for (int i = 0; i < array.Length; i++)
            {
                Console.WriteLine("Enter in a name and score: ");
                string userInput = Console.ReadLine();
                string[] parsedInput;
                parsedInput = userInput.Split(' ');
                string name = parsedInput[0];
                int score = int.Parse(parsedInput[1]);
                array[i] = score;
            }

为什么您需要将数组拆分为两个包含名称的数组和其他包含分数的数组。最好创建一个结构,其中字符串字段用于名称,整数字段用于得分,并编写比较器以对包含此数据结构类型元素的数组进行排序并对其进行排序。

它将解决您的所有问题,而且效率太高。

您使用的方法中没有太多数据完整性检查,但这是我用于拆分数组或任何类型的可枚举的扩展。 我没有对这些进行太多测试,所以我不能保证它们会起作用。 我已经删除了我所有的输入验证,但我建议你以自己的方式添加它们。

    public static List<List<T>> Split<T>(this IEnumerable<T> collection, Int32 groupSize)
    {
        var collectionList = collection.ToList();
        if (groupSize > collectionList.Count)
            groupSize = collectionList.Count;
        var chunks = new List<List<T>>();
        while (collectionList.Any())
        {
            var chunk = collectionList.Take(groupSize);
            chunks.Add(chunk.ToList());
            collectionList = collectionList.Skip(groupSize).ToList();
        }
        return chunks;
    }
    public static List<List<T>> Split<T>(this IEnumerable<T> collection, Func<T, Boolean> splitFunction)
    {
        var collectionList = collection.ToList();
        if (collectionList.IsNullOrEmpty())
            return new List<List<T>>();
        var indices = collectionList.FindIndices(splitFunction); // Custom method that searches for the indices that satisfy the predicate and returns the index of each matching item in the list.
        if (indices.IsNullOrEmpty()) // equivalent to indices == null || !indices.Any()
            return new List<List<T>> { collectionList };
        var chunks = new List<List<T>>();
        var lastIndex = 0;
        if (indices[0] > 0)
        {
            chunks.Add(collectionList.Take(indices[0]).ToList());
            lastIndex = indices[0];
        }
        for (var i = 1; i < indices.Count; i++)
        {
            var chunkSize = indices[i] - lastIndex;
            var chunk = collectionList.Skip(lastIndex).Take(chunkSize).ToList();
            if (chunk.IsNullOrEmpty())
            {
                break;
            }
            chunks.Add(chunk);
            lastIndex = indices[i];
        }
        if (collectionList.Count - lastIndex > 0)
        {
            var lastChunk = collectionList.Skip(lastIndex).ToList();
            chunks.Add(lastChunk);
        }
        return chunks;
    }