在 C# 中按字母顺序对数组进行排序 [英] Sorting an array alphabetically in C#
问题描述
希望有人能帮忙.我创建了一个可变长度数组,它将接受多个名称输入.我现在想按字母顺序对数组进行排序并将其返回到控制台屏幕.
Hope someone can help. I have created a variable length array that will accept several name inputs. I now want to sort the array in alphabetical order and return that to the console screen.
我认为 Array.Sort(names);会为我做这件事,但我抛出了一个异常.我一直在查看笔记、示例和在线内容,但似乎没有什么与我正在做的事情相匹配.
I thought that Array.Sort(names); would do this for me but I am getting an exception thrown. I have been looking at notes, examples and on-line but nothing seems to match what I am doing.
到目前为止,我已经完成了以下操作.我快要把头发扯掉了!PS 我一直在努力解决这个问题,我已经 30 多岁了,正在努力学习自己,所以请不要只说做你的功课"我哪里出错了.这是一个星期天,我正在努力做额外的工作,但没有笔记来准确地说明这一点
I have done the below so far. I am close to tearing my hair out here! PS I have been trying to figure this out for hours and I am 30+ years old trying to learn myself, so please don't just say "Do your homework" I have tried to resolve this and can not so I need someone to explain where I am going wrong. It is a Sunday and I am trying to do extra work and have no notes to cover this exactly
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Student_Array
{
class Program
{
struct Student
{
public string Name;
}
static void Main(string[] args)
{
int numberOfStudents;
Student[] names;
string input;
Console.WriteLine("How many students are there?");
input = Console.ReadLine();
numberOfStudents = int.Parse(input);
names = new Student[numberOfStudents];
for (int i = 0; i < names.Length; i++)
{
Student s;
Console.WriteLine("Please enter student {0}'s name", (i + 1));
s.Name = Console.ReadLine();
names[i] = s;
}
***Array.Sort<Student>(names);***
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i].Name);
}
}
}
}
推荐答案
这就能解决问题
Array.Sort(names, (x,y) => String.Compare(x.Name, y.Name));
这篇关于在 C# 中按字母顺序对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!