0

I am trying to make a basic console application that allows the user to input 3 names, and then sort it alphabetically. This is not working.

Here is my code.

Dim names(2) As String
    Console.WriteLine("Name 1 ?")
    names(0) = Console.ReadLine
    Console.WriteLine("Name 2 ?")
    names(1) = Console.ReadLine
    Console.WriteLine("Name 3 ?")
    names(2) = Console.ReadLine
    Array.Sort(names)

    Console.WriteLine("Your names are:" & names)  

The console is not printing the code.

2 Answers 2

4

Using LINQ:

Dim namesSorted() As String = names.OrderBy(Function(x) x).ToArray

With this approach you can change sort criteria to anything you want, i.e. word length, ascending/descending. To print the results:

Console.WriteLine("Your names are:" & String.Join(","c, namesSorted))

Also, I suggest you use List instead, then you are not limited to just 3 names, and you don't need to know how many names you will be processing in advance. LINQ syntax will be the same.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the assistance, is it possible recreating the same function using IF statements?
@user3215444: Everything is possible, but why would you want to go through the headache?
Very true, I'm assuming its not worth comparing each string with IF statements.
@user3215444: My advice - always go with highest level primitive of the language you are working with, VB.NET in this case, that allows you to do what you want. If you can avoid code complexity, i.e. loops, recursion this way, go for it. The above example is not more simple than Array.Sort, however, it's more extensible. So the concept you are getting is that your code does not change its core to support more functionality. Please note that LINQ is not always your best choice, because a LINQ query can grow complex very fast. Be careful when choosing your approach, think about extensibility.
1

Try something like this...

Dim names(2) As String
Console.WriteLine("Name 1 ?")
names(0) = Console.ReadLine
Console.WriteLine("Name 2 ?")
names(1) = Console.ReadLine
Console.WriteLine("Name 3 ?")
names(2) = Console.ReadLine
Array.Sort(names)
Console.WriteLine("Your names are:")
For x = 0 To 2
    Console.WriteLine(names(x)) 
Next x

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.