0

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

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

You could you OrderBy extension method.

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

1 Comment

This is the most in line with what I'm already working on, I'm trying this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.