-3

I am creating a small app that reads in a text file (stored as a string array) and sorts the contents by a simple key press. How can I assign a character eg. 'f' to show a certain array? For example I simply press 'f' and the console displays the first names of my text file i.e array[0]. Here is a snippet:

        //Console Read Key method???
        //
        if (key.KeyChar == 'f')
        {
            Console.WriteLine(strArray[0]);

        }

I realise there's lots of content on SO to do with this but nothing has been useful. It's a simple issue I can't work out! Don't worry about the sorting I simply need a specific array to show. Thanks for any help

ajm
  • 101
  • 2
  • 3
  • 15
  • 2
    Have a look at this SO post [Handle Key Press in console][1] [1]: http://stackoverflow.com/questions/8898182/how-to-handle-key-press-event-in-console-application – SteveB Nov 22 '13 at 16:51
  • **Did you try**, for example, with a simple foreach or a LINQ Where? Show us where it doesn't work... – Adriano Repetti Nov 22 '13 at 16:53
  • If you want to print out all the items in the array you could use something like "Array.ForEach( strArray, (line) => Console.WriteLine(line) );" – Marvin Smit Nov 22 '13 at 16:53
  • What's wrong with just using `Console.ReadKey()`? It's not as if you didn't know it exists. – Kendall Frey Nov 22 '13 at 16:56
  • Well basically i want to eventually sort by fields (name, lastname, age etc), with each field assigned to a letter so I can do: "if(a is pressed) {output this} else if (b is pressed) {output this}" etc etc – ajm Nov 22 '13 at 16:57

2 Answers2

2

Use the Console.ReadKey() method. It returns a ConsoleKeyInfo that you can check to see if the 'f' key was pressed.

http://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx

Fanblade
  • 451
  • 2
  • 9
1

Getting the key is very simple, you can use theConsole.ReadKey() method. This returns ConsoleKeyInfo which is a struct that contains the key that has been pressed.

You can use a Dictionary where the letter is the Key and the array is the Value.

David Pilkington
  • 13,528
  • 3
  • 41
  • 73