Clinton Kavai
Clinton Kavai

Reputation: 319

Sort an array of strings in ascending order in C#

I have an array of strings

string[] my_array = {"5:five", "8:eight","4:four", "7:seven","1:one", "6:six"};

I would like to have an output string like the one shown below, such that the values are concatenated in an ascending order

output_string = "onefourfivesixseveneight";

Here is my code

string [] args = {"5:five", "8:eight","4:four", "7:seven","1:one", 
                              "6:six" ,"840"};
            string outputString = "";
           int lowest_divisor = 1;
           int dividend = Convert.ToInt32(args[args.Length - 1]);
           for(int i = 0; i<args.Length - 1; i++)
               {

               string[] pairs = args[i].Split(":");

               int divisor = Convert.ToInt32(pairs[0]);

               string pairString = pairs[1];

               if(i == 0)
               {

                   lowest_divisor = divisor;
                   outputString = pairString;
               }
               else if(divisor <= lowest_divisor)
               {
                   outputString = pairString + outputString;
                   lowest_divisor = divisor;
               }
               else if(divisor > lowest_divisor)
               {
                  outputString = outputString + pairString;


               }
    }

Upvotes: 0

Views: 384

Answers (3)

skimad
skimad

Reputation: 307

This is little bit more verbose approach than the linq solutions provided.

      SortedDictionary<int, string> dict = new SortedDictionary<int, string>();
      foreach (string s in my_array)
       {
            string[] splitArr=s.Split(':');
            dict.Add(Convert.ToInt32(splitArr[0]), splitArr[1]);
        }            

        StringBuilder sb = new StringBuilder();
        foreach (KeyValuePair<int, string> kvp in dict)
        {
            sb.Append(kvp.Value);
        }
        string final=sb.ToString();

Upvotes: 3

Yair I
Yair I

Reputation: 1133

I think that the easiest way to do this is with linq. like this:

string outputString = string.Join("", args.OrderBy(x => int.Parse(x.Split(':')[0])).Select(x => x.Split(':').Length > 1 ? x.Split(':')[1] : ""));

if you don't control the content you can add checking to make sure it doesn't throw exception

Upvotes: 3

Broom
Broom

Reputation: 596

First we can limit to only the strings in the int:value format

IEnumerable<string> validStrings = my_array.Where(x => x.Contains(':') && int.TryParse(x.Split(':')[0], out int test));

Then we get the list ordered by the integer value

IEnumerable<string> orderedStrings = validStrings.OrderBy(x => int.Parse(x.Split(':')[0]));

Then we can combine them

string combined = string.Join("", orderedStrings.Select(x => x.Split(':')[1]));

Upvotes: 4

Related Questions