在C#中按字母顺序排序的数组 [英] Sorting an array alphabetically in C#
问题描述
希望有人可以提供帮助。
我创建了一个可变长度的数组,将接受若干名输入。
我现在要按照字母顺序排序的数组,并返回到控制台屏幕。
我认为的Array.Sort(地名);会做这对我来说,但我得到一个的异常。我一直在看笔记,例子和上线,但似乎没有任何匹配我在做什么。
我也做了以下为止。我靠近这里撕裂我的头发了!
PS我一直在试图弄清楚这一点了几个小时,我30多岁,想学我自己,所以请不要只说做好功课我试图解决这个,不能,所以我需要有人来解释我要去的地方错了。
这是一个星期天,我试图做额外的工作,没有任何票据,以支付这正是
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;命名空间Student_Array
{
类节目
{
学生结构
{
公共字符串名称;
} 静态无效的主要(字串[] args)
{
INT numberOfStudents;
学生[]的名称;
字符串输入; Console.WriteLine(有多少个学生?);
输入=到Console.ReadLine();
numberOfStudents = int.Parse(输入); 名称=新的学生[numberOfStudents]
的for(int i = 0; I< names.Length;我++)
{
学生们;
Console.WriteLine(请输入学生{0}名字,第(i + 1));
s.Name =到Console.ReadLine();
名称由[i] = S;
}
***的Array.Sort<的Student GT;(地名); ***
的for(int i = 0; I< names.Length;我++)
{ Console.WriteLine(名称[I] .Name点);
}
}
}
}
这应该做的伎俩
的Array.Sort(姓名,(X,Y)=>的String.Compare(x.Name,y.Name));
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.
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.
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);
}
}
}
}
This shall do the trick
Array.Sort(names, (x,y) => String.Compare(x.Name, y.Name));
这篇关于在C#中按字母顺序排序的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!