Saryk
Saryk

Reputation: 355

C# ordering array of strings

I have an array of strings that are formated as "ColX=Name=Value", where X is a number and X >= 4.

I'd like to sort the array in ascending order of that X, I tried using
int colNbr = int.parse(string.Split('=')[0].Substring(3))
to retreive the value of X, but then I don't know how to order the strings :/

Any easier recommendations appreciated :)

Upvotes: 0

Views: 85

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Try working with classes (anonymous ones in the context), not raw strings:

string[] source = ...

var data = source
  .Select(line => line.Split('='))
  .Select(items => new {           // Let's have classes
      Col = int.Parse(items[0].Substring(3)),
      Name = items[1],
      Value = items[2], })
  .OrderBy(item => item.Col);     // ... which are easy to handle (e.g. sort) 

Please, notice that if you decide to, say, sort by Name within the given Col all you have to do is to add .ThenBy(item => item.Name): classes are easy to maintain.

If you want to get the string[] back:

string[] sorted = data
  .Select(item => $"Col{item.Col},{item.Name},{item.Value}")
  .ToArray(); 

Upvotes: 1

Andrew
Andrew

Reputation: 354

You could you OrderBy extension method.

 string[] sortedArrayString = arrayOfString
   .OrderBy(str => int.parse(str.Split('=')[0].Substring(3)))
   .ToArray();

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29006

You are almost there with the logic, just wanted to make a try with OrderBy. Following code will help you to complete that?

List<string> inputList = SomeMethod(); // will populate the list
inputList = inputList.OrderBy(x=> int.parse(x.Split('=')[0].Substring(3))).ToList();

Upvotes: 1

Related Questions