user6609573
user6609573

Reputation:

Sorting an array of strings through the substring of each element C#

So, let's say I have an array of strings

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

I want to select the first numbers within each string element and sort this array in ascending order' I want the outcome to be when using:

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

Displaying: '3 Three, 6 Six and 8 Eight are the lowest elements'

Upvotes: 0

Views: 2145

Answers (4)

Slai
Slai

Reputation: 22866

Instead of splitting or parsing the strings, it is a bit more efficient to just sort by the index of the first space and then by the string:

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"

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460058

You can use String.Split and int.Parse with LINQ:

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

another more efficient but less readable way is Array.Sort:

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

Upvotes: 4

Akshey Bhat
Akshey Bhat

Reputation: 8545

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]))

Use the above code.

Upvotes: 0

Quentin Roger
Quentin Roger

Reputation: 6538

Something like this should do the trick

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

Or in your simple scenario :

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

Upvotes: 0

Related Questions