String to Array, Sort by 3rd word / column

I have a string with numbers, words and strings that I have split into an array.

If I ran Array.Sort(lines)

, it will sort an array of column 1 Number

.

How can I sort an array alphabetically by column 3 Color

,?


Note. These are not real columns, but just spaces separating words.

I cannot change the line to change the results.


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

      


FROM#

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 result of sorting the array

3 Earth Blue
1 Mercury Gray
4 Mars Red
2 Venus Yellow

      

+3


source to share


3 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!

+4


source


Alex got a direct answer - I just wanted to bring something from a different angle.

This code is good from academic, just learning a conceptual point of view.

But if you want to translate this into something for a business developer, you have to get used to structuring it like:

  • Developing the Planet class
  • A function that returns a planet from a source string
  • You have a function that displays the Planet as you plan to display it.


There are many reasons for this, but the big one is that you will have reusable flexible code (look at the function you are currently writing - how likely is it that you can reuse this down the line for something else?) If you are wondering , see SRP (Single Responsibility Principle) for more information on this concept.

This is the 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.

+2


source


You can use an overload Array.Sort

that accepts a custom mapper:

public class MyComparer : IComparer  {
      int IComparer.Compare( Object x, Object y )  {
          //compare last parts here
      }
}

      

0


source







All Articles