vb.net Visual Basic 字符串数组按字母顺序排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21236454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:29:45  来源:igfitidea点击:

Visual Basic String Array Alphabetical Sort

arraysvb.netstringsorting

提问by LyanR

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.

我正在尝试制作一个基本的控制台应用程序,它允许用户输入 3 个名称,然后按字母顺序对其进行排序。这是行不通的。

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.

控制台不打印代码。

回答by Neolisk

Using LINQ:

使用 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.

另外,我建议你改用List,这样你就不仅限于3个名字,而且你不需要提前知道你将处理多少个名字。LINQ 语法将是相同的。

回答by chris_techno25

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