通过c#从文本文件中删除相同的行

发布于 2024-09-02 06:28:29 字数 38 浏览 2 评论 0原文

如何使用 C# 删除文件 .txt 中的相同行但保留其中一行?

how to delete same lines in file .txt but keep one of them using c# ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我的影子我的梦 2024-09-09 06:28:29

逐行阅读。将该行添加到 HashSet,并且 Add 返回 true,将该行打印到输出。

Read line by line. Add the line to a HashSet, and Add returns true, print the line to the output.

╰つ倒转 2024-09-09 06:28:29

有很多方法。一种可能是使用 Set 的某些版本。请参阅 C# Set 集合? 了解这一点。

如果所有相同的行都相继出现,您可以迭代并查看该行是否与最后一行匹配。如果是,请将其丢弃。

There are many ways. One could be to use some version of a Set. Look at C# Set collection? for this.

If all the same lines are after one another, you could just iterate through and see if the line matches the last line. If it does, discard it.

软甜啾 2024-09-09 06:28:29

您的代码将如下所示:

  1. 对于输入文件中的每一行。
  2. 如果当前行不相同
    与上一行一样,将其写入
    输出文件。
  3. 将当前行设置为等于
    上一行。

这假设重复的行是相邻的。如果它们不相邻,则必须先对文件进行排序。

Your code would look something like this:

  1. For each line in the input file.
  2. If the current line is not the same
    as the previous line, write it to
    the output file.
  3. Set the current line equal to the
    previous line.

This assumes that duplicate lines are adjacent. If they are not adjacent, you will have to sort the file first.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文