Sorting an array alphabetically in C#

后端 未结 7 906
孤街浪徒
孤街浪徒 2020-12-09 17:12

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

7条回答
  •  攒了一身酷
    2020-12-09 17:37

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

        struct Student : IComparable
        {
            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...

    Array.Sort(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();
    

提交回复
热议问题