4

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'.

5
  • 1
    Not exactly sure what you expect from "a".OrderBy(x => x)... Please doublecheck your code reflects what you think it is doing. Commented Feb 28, 2019 at 2:02
  • in the variable sOutput 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' Commented Feb 28, 2019 at 2:11
  • orden is a string, so any LINQ on it will work on the letters, i.e. calling OrderBy on a string will sort the letters. As a side node: don’t use ArrayList which is obsolete for more than 10 years now – use the strongly-typed List<T> (here List<string>) class. Or if you want your list to be sorted when you insert items into it use SortedList<T>. Commented Feb 28, 2019 at 2:59
  • There's no reason to use ArrayList anymore, it's obsolete. You can use a string[] in this case, and you can also get rid of the streamreader and do: string[] arrText = File.ReadAllLines(filePath); Commented Feb 28, 2019 at 3:03
  • Thank you very much for the recommendations Commented Feb 28, 2019 at 3:14

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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);
    }
}

4 Comments

Thank you very much for your answer, I have an error the name ReadKey does exist in the current context
@ThomasCaycedoMartinez Should be Console.ReadKey.
@ThomasCaycedoMartinez I added the missing part. I actually wrote it with using static System.Console;
I'd use bool? ascending = null; to eliminate the need for chosen. Cuts the lines and the complexity.
1

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)));

Comments

0

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();
    }

3 Comments

Though, he, and for the matter nobody, should use ArrayList anymore as it’s just obsolete for a long time now.
I absolutely agree and would up vote your comment if SO allowed such things :)
Whoops SO does allow for up voting comments, learn something new every day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.