Order string alphabetically

I'm reading a .txt file using C #, this file has a list of words, I need to sort the list alphabetically

static void Main(string[] args)
{
    StreamReader objReader = new StreamReader(
        @"C:\Users\thoma\Documents\Visual Studio 2019\Backup Files\data.txt");

    string orden = "";
    ArrayList arrText = new ArrayList();

    while (orden != null)
    {
        orden = objReader.ReadLine();
        if (orden != null) arrText.Add(orden);
    }
    objReader.Close();

    foreach (string sOutput in arrText)
        Console.WriteLine(sOutput);

    Console.WriteLine("Order alphabetically descendant press 'a': ");
    Console.WriteLine("Ordener ascending alphabetical press 'b': ");

    orden = Console.ReadLine();

    switch (orden)
    {
        case "a":
             string ordenado = new String(orden.OrderBy(x => x).ToArray());
            Console.WriteLine(ordenado);
            break;
        case "b":
            Console.WriteLine("");
            break;
    }

    Console.ReadLine();
}

This is the code that I have up to this moment. The .txt file shows it without problems but when entering the while statement and press the option, it does not return anything.

In arrText are stored the words of the .txt file, these words are: 'in' 'while' 'are'.

I need that in the while statement when the 'a' key is pressed, show me the list of words but in alphabetical order: 'are' 'in' 'while'.

Upvotes: 4

Views: 466

Answers (4)

Canica
Canica

Reputation: 2738

This should also work with minimal changes to the sample code provided.

First, change ArrayList to List<string>

List<string> arrText = new List<string>();

Second, order using the List OrderBy or OrderByDescending method

string ordenado = string.Format("{0}{1}{0}", "'", string.Join("','", arrText.OrderBy(x => x)));

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117037

I'd offer a slightly better separated and shortened version:

    var choices = new Dictionary<ConsoleKey, bool?>()
    {
        { ConsoleKey.D1, true },
        { ConsoleKey.D2, false }
    };

    var ascending = (bool?)null;
    while (ascending == null)
    {
        Console.WriteLine("Please choose between ascending and descending order.");
        Console.WriteLine("Press 1 for ascending");
        Console.WriteLine("Press 2 for descending");
        var choice = Console.ReadKey(true);
        ascending = choices.ContainsKey(choice.Key) ? choices[choice.Key] : null;
    }

    var lines = File.ReadAllLines("c:/data.txt");
    lines = ascending.Value
        ? lines.OrderBy(x => x).ToArray()
        : lines.OrderByDescending(x => x).ToArray();

    foreach (var line in lines)
    {
        Console.WriteLine(line);
    }
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);

Or even this:

    var choices = new Dictionary<ConsoleKey, Func<string[], string[]>>()
    {
        { ConsoleKey.D1, xs => xs.OrderBy(x => x).ToArray() },
        { ConsoleKey.D2, xs => xs.OrderByDescending(x => x).ToArray() }
    };

    var ascending = (Func<string[], string[]>)null;
    while (ascending == null)
    {
        Console.WriteLine("Please choose between ascending and descending order.");
        Console.WriteLine("Press 1 for ascending");
        Console.WriteLine("Press 2 for descending");
        var choice = Console.ReadKey(true);
        ascending = choices.ContainsKey(choice.Key) ? choices[choice.Key] : null;
    }

    var lines = ascending(File.ReadAllLines("c:/data.txt"));

    foreach (var line in lines)
    {
        Console.WriteLine(line);
    }
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);

Upvotes: 3

ChaosPandion
ChaosPandion

Reputation: 78262

Here is my take on your question. Notice that I'm asking about the sort order before you loop the text from the file.

using System.Linq;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var lines = File.ReadAllLines("c:/data.txt");
        var ascending = false;
        var chosen = false;
        do
        {
            Console.WriteLine("Please choose between ascending and descending order.");
            Console.WriteLine("Press 1 for ascending");
            Console.WriteLine("Press 2 for descending");
            var choice = Console.ReadKey(true);
            switch (choice.Key)
            {
                case ConsoleKey.D1:
                    ascending = true;
                    chosen = true;
                    break;
                case ConsoleKey.D2:
                    ascending = false;
                    chosen = true;
                    break;
                default:
                    Console.WriteLine("Invalid Choice");
                    break;
            }
        } while (!chosen);
        var sequence = ascending 
            ? lines.OrderBy(x => x) 
            : lines.OrderByDescending(x => x);
        foreach (var line in sequence)
        {
            Console.WriteLine(line);
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey(true);
    }
}

Upvotes: 2

vscoder
vscoder

Reputation: 1007

Sticking with the original theme of using an ArrayList, the List is much more flexible, but if you must then you need to deal with the limitations of that type.

    public static void Main()
    {
        StreamReader objReader = new StreamReader(@"C:\\Temp\\data.txt");
        string orden = "";
        ArrayList arrText = new ArrayList();
        while (orden != null)
        {
            orden = objReader.ReadLine();
            if (orden != null)
                arrText.Add(orden);
        }
        objReader.Close();
        foreach (string sOutput in arrText)
        { Console.WriteLine(sOutput); }
        Console.WriteLine("Order alphabetically descendant press 'a': ");
        Console.WriteLine("Ordener ascending alphabetical press 'b': ");
        orden = Console.ReadLine();
        switch (orden)
        {
            case "a":
                arrText.Sort();
                break;
            case "b":
                arrText.Sort();
                arrText.Reverse();
                break;
        }

        foreach (string sTemp in arrText)
        { Console.Write(sTemp); }
        Console.WriteLine();
        Console.ReadLine();
    }

Upvotes: 0

Related Questions