Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Array, Sort by 3rd Word/Column

I have a string with numbers, words, and linebreaks that I split into an Array.

If I run Array.Sort(lines) it will sort the Array numerically by Column 1, Number.

How can I instead sort the Array alphabetically by Column 3, Color?


Note: They are not real columns, just spaces separating the words.

I cannot modify the string to change the results.


| Number     | Name       | Color      |
|------------|------------|------------|
| 1          | Mercury    | Gray       |
| 2          | Venus      | Yellow     |
| 3          | Earth      | Blue       |
| 4          | Mars       | Red        |

C#

Example: http://rextester.com/LSP53065

string planets = "1 Mercury Gray\n"
               + "2 Venus Yellow\n"
               + "3 Earth Blue\n"
               + "4 Mars Red\n";


// Split String into Array by LineBreak
string[] lines = planets.Split(new string[] { "\n" }, StringSplitOptions.None);


// Sort
Array.Sort(lines);


// Result
foreach(var line in lines)
{
    Console.WriteLine(line.ToString());
}

Desired Sorted Array Result

3 Earth Blue
1 Mercury Gray
4 Mars Red
2 Venus Yellow
like image 784
Matt McManis Avatar asked Sep 10 '26 01:09

Matt McManis


2 Answers

Try this code:

string planets = "1 Mercury Gray \n"
                    + "2 Venus Yellow \n"
                    + "3 Earth Blue \n"
                    + "4 Mars Red \n";

var lines = planets.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
    .OrderBy(s => s.Split(' ')[2])
    .ToArray();

foreach (var line in lines)
{
    Console.WriteLine(line);
}

EDIT: Thanks @Kevin!

like image 194
Aleks Andreev Avatar answered Sep 11 '26 13:09

Aleks Andreev


Aleks has got the straight-up answer - I just wanted to contribute something from another angle.

This code is fine from an academic, just learning the concepts point of view.

But if you're looking to translate this into something for business dev, you should get in the habit of structuring it like:

  • Develop a Planet class
  • Have a function that returns a Planet from a source text line
  • Have a function that displays a Planet how you intend it to be displayed.

There are a lot of reasons for this, but the big one is that you'll have reusable, flexible code (look at the function you're writing right now - how likely is it that you'll be able to reuse it down the line for something else?) If you're interested, look up some info on SRP (Single Responsibility Principle) to get more info on this concept.

This is a translated version of your code:

    static void Main(string[] args)
    {
        string planetsDBStr = "1 Mercury Gray \n"
                + "2 Venus Yellow \n"
                + "3 Earth Blue \n"
                + "4 Mars Red \n";

        List<Planet> planets = GetPlanetsFromDBString(planetsDBStr);

        foreach (Planet p in planets.OrderBy(x => x.color))
        {
            Console.WriteLine(p.ToString());
        }
        Console.ReadKey();

    }

    private static List<Planet> GetPlanetsFromDBString(string dbString)
    {
        List<Planet> retVal = new List<Planet>();
        string[] lines = dbString.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        foreach (string line in lines)
            retVal.Add(new Planet(line));
        return retVal;
    }

    public class Planet
    {
        public int orderInSystem;
        public string name;
        public string color;
        public Planet(string databaseTextLine)
        {
            string[] parts = databaseTextLine.Split(' ');
            this.orderInSystem = int.Parse(parts[0]);
            this.name = parts[1];
            this.color = parts[2];
        }
        public override string ToString()
        {
            return orderInSystem + " " + name + " " + color;
        }
    }

EDIT: Fixed some formatting issues

like image 36
Kevin Avatar answered Sep 11 '26 15:09

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!