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'.
"a".OrderBy(x => x)... Please doublecheck your code reflects what you think it is doing.ordenis 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 useSortedList<T>.ArrayListanymore, it's obsolete. You can use astring[]in this case, and you can also get rid of the streamreader and do:string[] arrText = File.ReadAllLines(filePath);