how to sort a string array by alphabet?

前端 未结 3 1937
轻奢々
轻奢々 2021-01-17 21:59

I\'ve got a array of many strings. How can I sort the strings by alphabet?

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 22:12

    Array.Sort also provides a Predicate-Overload. You can specify your sorting-behaviour there:

    Array.Sort(myArray, (p, q) => p[0].CompareTo(q[0]));
    

    You can also use LINQ to Sort your array:

    string[] myArray = ...;
    string[] sorted = myArray.OrderBy(o => o).ToArray();
    

    LINQ also empoweres you to sort a 2D-Array:

    string[,] myArray = ...;
    string[,] sorted = myArray.OrderBy(o => o[ROWINDEX]).ThenBy(t => t[ROWINDEX]).ToArray();
    

    The default sorting-behaviour of LINQ is also alphabetically. You can reverse this by using OrderByDescending() / ThenByDescending() instead.

提交回复
热议问题