1

I have a problem statement given below;

inputArray = {"rajesh|51|32|asd", "nitin|71|27|asd", "test|11|30|asd"}

It is a input array and I need to sort this Sting Array[] in ascending order based on the number next to Name in each string, So the returned output Array should like like this;

output =  {"test|11|30|asd", "rajesh|51|32|asd" ,"nitin|71|27|asd"} 

I tried below code but I am not able to write the complete code as I am stuck at some point, What should I use to get the desired sorted output Array?

int sort = 0;
foreach(string s in inputArray)
{
  string[] foo = s.split("|");
  
  int orderNum = Convert.ToInt32(foo[1])
  
  if(sort<orderNum)
    sort = orderNum; 
  //stuck here..
}

2 Answers 2

2

Just use Linq:

    //input array
    var input = new string[]  {
        "test|11|30|asd", 
        "rajesh|51|32|asd",
        "nitin|71|27|asd"
    };

    //sorter
    var output = input.OrderBy(s => int.Parse(s.Split('|')[1]));

    //dump the resulting list
    foreach (string s in output) {
        Console.WriteLine(s);
    }
Sign up to request clarification or add additional context in comments.

6 Comments

You're right, I thought the problem is not only sorting :) This is the correct solution unless we don't know something
@Fabjan no prob, I re-read the question in order to have misunderstood something!
what if we do not want to use Linq?
Then I guess you would have to implement IComparer interface and use Array.Sort or even write your own sorting algorithm.
@RahulNagrale Fabjan is right, but why not using it? I don't see any valid reason to avoid it.
|
1

If you want to sort in place, you should to use the Array.Sort function

Array.Sort(inputArray, (s1, s2) =>
    int.Parse(s1.split("|")[1].CompareTo(int.Parse(s2.split("|")[1])
);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.