在 C# 中按字母顺序对数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16636554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:31:51  来源:igfitidea点击:

Sorting an array alphabetically in C#

c#arrayssorting

提问by user001

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.

我认为 Array.Sort(names); 会为我做这件事,但我抛出了一个异常。我一直在查看笔记、示例和在线内容,但似乎没有什么与我正在做的事情相匹配。

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

到目前为止,我已经完成了以下工作。我快要把头发扯掉了!PS 我一直在努力解决这个问题,我已经 30 多岁了,正在努力学习自己,所以请不要只说“做你的功课”我哪里出错了。这是一个星期天,我正在努力做额外的工作,但没有笔记来准确地涵盖这一点

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

采纳答案by oleksii

This shall do the trick

这将解决问题

Array.Sort(names, (x,y) => String.Compare(x.Name, y.Name));

回答by Douglas

Your issue here might be that you are confusing the notions of students and names. By defining the Studentstruct, you are creating an entity that can represent more than a mere name. You could, for example, extend it to include Age, Hometown, and so forth. (For this reason, it might be more meaningful to name your array studentsrather than names.)

您在这里的问题可能是您混淆了学生和姓名的概念。通过定义Student结构,您正在创建一个可以表示的不仅仅是名称的实体。例如,您可以将其扩展为包括AgeHometown等。(出于这个原因,命名数组可能students比命名更有意义names。)

struct Student
{
    public string Name;
    public int Age;
    public string Hometown;
}

Given the possibility of multiple fields, the Array.Sortmethod needs to know what you want to sort your list upon. Do you want students ordered by name, by age, or by hometown?

考虑到多个字段的可能性,该Array.Sort方法需要知道您想根据什么对列表进行排序。您希望学生按姓名、年龄或家乡排序吗?

Per the MSDN documentation on Array.Sort<T>:

根据 MSDN 文档Array.Sort<T>

Sorts the elements in an entire Arrayusing the IComparable<T>generic interface implementation of each element of the Array.

Array使用IComparable<T>Array 的每个元素的通用接口实现对整个元素进行排序。

This means that the type you are attempting to sort – in your case, Student– must implement the IComparable<T>interface, in order for the Array.Sortimplementation to know how it should compare two Studentinstances. If you're convinced that students will always be sorted by name, you could implement it like so:

这意味着您尝试排序的类型 - 在您的情况下Student- 必须实现IComparable<T>接口,以便Array.Sort实现知道它应该如何比较两个Student实例。如果您确信学生将始终按姓名排序,您可以像这样实现它:

struct Student : IComparable<Student>
{
    public string Name;
    public int Age;
    public string Hometown;

    public int CompareTo(Student other)
    {
        return String.Compare(this.Name, other.Name);
    }
}

Alternatively, you could provide a function that extracts the sort key to the sort method itself. The easiest way of achieving this is through the LINQ OrderBymethod:

或者,您可以提供一个将排序键提取到排序方法本身的函数。实现这一点的最简单方法是通过 LINQOrderBy方法:

names = names.OrderBy(s => s.Name).ToArray();

回答by Elle

To sort by the nameproperty of your Studentobjects in your Studentarray, you can use

要按数组中对象的name属性排序,您可以使用StudentStudent

Array.Sort(names, (s1, s2) => String.Compare(s1.Name, s2.Name));

which will sort your array in place, or with System.Linq:

它将对您的数组进行排序,或者使用System.Linq

names = names.OrderBy(s => s.Name).ToArray();

which can return the sorted IEnumerableas an array (.ToArray()) or a list (.ToList().)

它可以返回排序IEnumerable为数组 ( .ToArray()) 或列表 ( .ToList().)

Remember to sort case-insensitive if it matters, as pointed out in another answer, which can be done in String.Comparelike so:

如果重要,请记住对不区分大小写进行排序,正如另一个答案中所指出的那样,可以这样做String.Compare

String.Compare(s1.Name, s2.Name, StringComparison.CurrentCultureIgnoreCase)

回答by Marian-Emanuel Ionascu

you can find one of the basics algorithms here : Simple bubble sort c#

你可以在这里找到一种基本算法:简单的冒泡排序 c#

you have to do some modifications , that example is for int, for string you must compare the names.

您必须进行一些修改,该示例适用于 int,对于字符串,您必须比较名称。

you can find better algorithms for sorting. for now bubble sort is ok for you.

你可以找到更好的排序算法。现在冒泡排序适合你。

回答by cvraman

You can use this as well, instead of using Array.Sort.

您也可以使用它,而不是使用 Array.Sort。

names = names.OrderBy(p => p.Name).ToArray();

回答by Joachim Isaksson

You can either use Sortas is if you extend Student to implement IComparable;

Sort如果您扩展 Student 以实现 IComparable,您可以按原样使用;

    struct Student : IComparable<Student>
    {
        public string Name;
        public int CompareTo(Student other)
        {
            return String.Compare(Name, other.Name,
                   StringComparison.CurrentCultureIgnoreCase);
        }
    }

...or you can pass a compare lambda into Sort...

...或者您可以将比较 lambda 传递到 Sort ...

Array.Sort<Student>(names, (x, y) => String.Compare(x.Name, y.Name,
                                     StringComparison.CurrentCultureIgnoreCase));

...or as a third option just create a new, sorted, array;

...或者作为第三种选择,只需创建一个新的、已排序的数组;

var newArray = names.OrderBy(x => x.Name.ToLower()).ToArray();

回答by Raz Megrelidze

Create a comparer class

创建一个比较器类

class StudentComparer : IComparer<Student>
{
    public int Compare(Student a, Student b)
    {
        return a.Name.CompareTo(b.Name);
    }
}

Sort:

种类:

Array.Sort(students,new StudentComparer());