【发布时间】:2019-02-28 01:58:07
【问题描述】:
我正在使用 C# 读取一个 .txt 文件,这个文件有一个单词列表,我需要按字母顺序对列表进行排序
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();
}
这是我到现在为止的代码。 .txt 文件显示它没有问题,但是当输入 while 语句并按下选项时,它不会返回任何内容。
在arrText中存储了.txt文件的单词,这些单词是:'in' 'while' 'are'。
当按下'a'键时,我需要在while语句中显示单词列表,但按字母顺序:'are''in''while'。
【问题讨论】:
-
不确定您对
"a".OrderBy(x => x)的期望...请仔细检查您的代码是否反映了您认为它在做什么。 -
变量sOutput中存放的是.txt文件的单词,这些单词是:'in' 'while' 'are'。当按下“a”键时,我需要在 while 语句中显示单词列表,但按字母顺序排列:“are”“in”“while”
-
orden是一个字符串,所以它上面的任何 LINQ 都可以处理字母,即在字符串上调用 OrderBy 将对字母进行排序。作为辅助节点:不要使用已经过时 10 多年的 ArrayList - 使用强类型 List(此处为 List )类。或者,如果您希望在插入项目时对列表进行排序,请使用 SortedList<T>。 -
没有理由再使用
ArrayList,它已经过时了。在这种情况下,您可以使用string[],也可以摆脱流式阅读器并执行以下操作:string[] arrText = File.ReadAllLines(filePath); -
非常感谢您的建议