【问题标题】:Order string alphabetically按字母顺序排列字符串
【发布时间】: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);
  • 非常感谢您的建议

标签: c# .net


【解决方案1】:

我会提供一个更好的分离和缩短版本:

    var choices = new Dictionary<ConsoleKey, bool?>()
    {
        { ConsoleKey.D1, true },
        { ConsoleKey.D2, false }
    };

    var ascending = (bool?)null;
    while (ascending == null)
    {
        Console.WriteLine("Please choose between ascending and descending order.");
        Console.WriteLine("Press 1 for ascending");
        Console.WriteLine("Press 2 for descending");
        var choice = Console.ReadKey(true);
        ascending = choices.ContainsKey(choice.Key) ? choices[choice.Key] : null;
    }

    var lines = File.ReadAllLines("c:/data.txt");
    lines = ascending.Value
        ? lines.OrderBy(x => x).ToArray()
        : lines.OrderByDescending(x => x).ToArray();

    foreach (var line in lines)
    {
        Console.WriteLine(line);
    }
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);

甚至这个:

    var choices = new Dictionary<ConsoleKey, Func<string[], string[]>>()
    {
        { ConsoleKey.D1, xs => xs.OrderBy(x => x).ToArray() },
        { ConsoleKey.D2, xs => xs.OrderByDescending(x => x).ToArray() }
    };

    var ascending = (Func<string[], string[]>)null;
    while (ascending == null)
    {
        Console.WriteLine("Please choose between ascending and descending order.");
        Console.WriteLine("Press 1 for ascending");
        Console.WriteLine("Press 2 for descending");
        var choice = Console.ReadKey(true);
        ascending = choices.ContainsKey(choice.Key) ? choices[choice.Key] : null;
    }

    var lines = ascending(File.ReadAllLines("c:/data.txt"));

    foreach (var line in lines)
    {
        Console.WriteLine(line);
    }
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);

【讨论】:

    【解决方案2】:

    这是我对您的问题的看法。请注意,我在从文件中循环文本之前询问排序顺序。

    using System.Linq;
    using System.IO;
    
    class Program
    {
        static void Main(string[] args)
        {
            var lines = File.ReadAllLines("c:/data.txt");
            var ascending = false;
            var chosen = false;
            do
            {
                Console.WriteLine("Please choose between ascending and descending order.");
                Console.WriteLine("Press 1 for ascending");
                Console.WriteLine("Press 2 for descending");
                var choice = Console.ReadKey(true);
                switch (choice.Key)
                {
                    case ConsoleKey.D1:
                        ascending = true;
                        chosen = true;
                        break;
                    case ConsoleKey.D2:
                        ascending = false;
                        chosen = true;
                        break;
                    default:
                        Console.WriteLine("Invalid Choice");
                        break;
                }
            } while (!chosen);
            var sequence = ascending 
                ? lines.OrderBy(x => x) 
                : lines.OrderByDescending(x => x);
            foreach (var line in sequence)
            {
                Console.WriteLine(line);
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
    }
    

    【讨论】:

    • 非常感谢您的回答,我有一个错误,名称 ReadKey 在当前上下文中确实存在
    • @ThomasCaycedoMartinez 应该是 Console.ReadKey
    • @ThomasCaycedoMartinez 我添加了缺失的部分。我实际上是用using static System.Console;写的
    • 我会使用bool? ascending = null; 来消除对chosen 的需要。减少线条和复杂性。
    【解决方案3】:

    这也应该在对提供的示例代码进行最小更改的情况下工作。

    首先,将ArrayList改为List&lt;string&gt;

    List<string> arrText = new List<string>();
    

    二、使用List OrderBy或OrderByDescending方法排序

    string ordenado = string.Format("{0}{1}{0}", "'", string.Join("','", arrText.OrderBy(x => x)));
    

    【讨论】:

      【解决方案4】:

      坚持使用 ArrayList 的原始主题,List 更加灵活,但如果必须,则需要处理该类型的限制。

          public static void Main()
          {
              StreamReader objReader = new StreamReader(@"C:\\Temp\\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":
                      arrText.Sort();
                      break;
                  case "b":
                      arrText.Sort();
                      arrText.Reverse();
                      break;
              }
      
              foreach (string sTemp in arrText)
              { Console.Write(sTemp); }
              Console.WriteLine();
              Console.ReadLine();
          }
      

      【讨论】:

      • 尽管如此,他和任何人都应该不再使用 ArrayList,因为它已经过时了很长时间。
      • 我绝对同意,如果允许这样的事情,我会投票赞成你的评论:)
      • 哎呀,确实允许投票的 cmets,每天学习新东西。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      相关资源
      最近更新 更多