通过每个元素C#的子字符串对字符串数组进行排序

时间:2016-08-22 10:50:53

标签: c# arrays sorting

所以,假设我有一个字符串数组

    string[] stringArray = new string[5] { "3 Three", "8 Eight", "6 Six", "13 Thirteen", "24 Twenty Four";

我想选择每个字符串元素中的第一个数字,并按升序对此数组进行排序 我希望结果是在使用时:

    Console.Writeline(String.Format("{0}, {1} and {2} are the lowest elements", stringArray[0], stringArray[1], stringArray[2]))

显示: '3 Three,6 Six和8 Eight是最低元素'

4 个答案:

答案 0 :(得分:3)

您可以将String.Splitint.Parse与LINQ:

一起使用
stringArray = stringArray.OrderBy(s => int.Parse(s.Split()[0])).ToArray();

另一种更有效但不太可读的方式是Array.Sort

Array.Sort(stringArray, (s1, s2) => int.Parse(s1.Split()[0]).CompareTo(int.Parse(s2.Split()[0])));

答案 1 :(得分:0)

这样的事情可以解决问题

  string[] stringArray = new string[5] { "3 Three", "8 Eight", "6 Six", "13 Thirteen", "24 Twenty Four" };
  var ordered = stringArray.Select(s => new { number = int.Parse(s.Split(' ')[0]), text = s.Split(' ')[1] }).OrderBy(i => i.number).Select(arg => arg.number + " " + arg.text).ToArray();
  Console.WriteLine($"{ordered[0]}, {ordered[1]} and {ordered[2]} are the lowest elements");

或者在您的简单场景中:

var ordered = stringArray.OrderBy(s => int.Parse(s.Split(' ')[0])).ToArray();
Console.WriteLine($"{ordered[0]}, {ordered[1]} and {ordered[2]} are the lowest elements");

答案 2 :(得分:0)

string[] stringArray = new string[5] { "3 Three", "8 Eight", "6 Six", "13 Thirteen", "24 Twenty Four"};
string[] orderedArray = stringArray.OrderBy(ele => Convert.ToInt32(ele.Split(' ')[0])).ToArray();

Console.Writeline(String.Format("{0}, {1} and {2} are the lowest elements", orderedArray[0], orderedArray[1], orderedArray[2]))

使用上面的代码。

答案 3 :(得分:0)

不是拆分或解析字符串,而是按第一个空格的索引排序,然后按字符串排序更有效:

string[] stringArray = { "3 Three", "8 Eight", "6 Six", "13 Thirteen", "24 Twenty Four" };

var ordered = stringArray.OrderBy(s => s.IndexOf(' ')).ThenBy(s => s).ToArray();

Debug.Print(string.Join(", ", ordered)); // "3 Three, 6 Six, 8 Eight, 13 Thirteen, 24 Twenty Four"