简体   繁体   English

在控制台中使用C#从文本文件订购writeline输出

[英]Ordering writeline outputs from text file using C# in console

I wonder if you could help me at all. 我想知道您是否能帮助我。 Essentially my program has to scan through a text file and then print the lines. 本质上,我的程序必须扫描文本文件,然后打印行。 Each line that is printed must be alphabetized also, if possible. 如果可能,打印的每一行也必须按字母顺序排列。 I could do with being able to point at any file through cmd rather than automatically pointing it at a specific file and in a specific location. 我可以通过cmd指向任何文件,而不是自动将其指向特定文件和特定位置。

I have this so far as I wanted to get things working in a basic form. 到目前为止,我一直想以一种基本的形式来完成工作。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Program
{
class Program
{
    static void Main(string[] args)
    {
        String line;
        try
        {
            //We Have to pass the file path and packages.txt filename to the StreamReader constructor
            StreamReader sr = new StreamReader("D:\\Users\\James\\Desktop\\packages.txt");

            //Instruction to read the first line of text
            line = sr.ReadLine();

            //Further Instruction is to to read until you reach end of file
            while (line != null)
            {
                //Instruction to write the line to console window
                Console.WriteLine(line);
                //The read the next line
                line = sr.ReadLine();
            }

            //Finally close the file
            sr.Close();
            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }
    }
}
}

I hope you guys can help me, I am very rusty! 我希望你们能帮助我,我很生锈!

My thoughts were to convert the string into an char array? 我的想法是将字符串转换为char数组? then modify and sort using array.sort method. 然后使用array.sort方法进行修改和排序。

OK guys. 好了朋友们。 On your advice I have made a few changes. 根据您的建议,我进行了一些更改。 I get an exception thrown at me now as we are trying to get it to accept an argument in order for us to point it at any text file, not a specific one. 我现在正在抛出一个异常,因为我们试图让它接受一个参数,以便我们将其指向任何文本文件,而不是特定的文件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Program
{
class Program
{
    static void Main (params string[] args)
    {
        string PathToFile = args[1];
        string TargetPackages = args[2];

        try

        {

            string[] textLines = File.ReadAllLines(PathToFile);
            List<string> results = new List<string>();

            foreach (string line in textLines)
            {
                if (line.Contains(TargetPackages))
                {
                    results.Add(line);
                }

                Console.WriteLine(results);
            }
        }


        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }
    }
}
}

If you just want to sort by the first word and output, you need to read all the lines into memory (I hope your file isn't too large), sort the lines, and then write them back out. 如果只想按第一个单词排序并输出,则需要将所有行读入内存(我希望您的文件不要太大),对行进行排序,然后再将其写回。

There are many ways to do all that. 有很多方法可以做到所有这些。 The File class has some helper functions that make reading and writing text files line-by-line very simple, and LINQ's OrderBy method makes quick work of sorting things. File类具有一些帮助程序功能,这些功能使逐行读取和写入文本文件变得非常简单,而LINQ的OrderBy方法可快速进行排序。

File.WriteAllLines(
    outputFileName,
    File.ReadLines(inputFileName).OrderBy(line => line));

See File.WriteAllLines and File.ReadLines for information on how they work. 有关它们如何工作的信息,请参见File.WriteAllLinesFile.ReadLines

If you want to load each line, sort the first word, and then re-output the line: 如果要加载每一行,请对第一个单词进行排序,然后重新输出该行:

File.WriteAllLines(
    outputFileName,
    File.ReadLines(inputFileName)
        .Select(line =>
            {
                var splits = line.Split(new [] {' '}};
                var firstWord = new string(splits[0].OrderBy(c => c));
                var newLine = firstWord + line.Substring(firstWord.Length);
                return newLine;
            }));

Note that this loads and processes one line at a time, so you don't have to hold the entire file in memory. 请注意,这一次加载和处理一行,因此您不必将整个文件保存在内存中。

You should be better off by reading all lines at once and then looking at each line separately, like this: 最好一次阅读所有行,然后分别查看每一行,这样会更好:

List<string> allLines = System.IO.File.ReadLines(pathToFile).ToList();
allLines = allLines.OrderBy(line => line).ToList(); //this orders alphabetically all your lines
foreach (string line in allLines)
{
    Console.WriteLine(line);
}

This will print all the lines in the file ordered alphabetically. 这将按字母顺序打印文件中的所有行。

You can also parametrize the path by using the args parameter you receive when opening the application: 您还可以使用打开应用程序时收到的args参数对路径进行参数设置:

CMD> pathToYourExe.exe path1 path2 path3

You can mock this by using the DEBUG arguments in the project's Debug menu 您可以使用项目的“调试”菜单中的DEBUG参数来对此进行模拟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM