Sorting an array alphabetically in C#

后端 未结 7 910
孤街浪徒
孤街浪徒 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:38

    To sort by the name property of your Student objects in your Student array, you can use

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

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

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

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

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

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

提交回复
热议问题