C# - 在文本文件中删除重复的行

4

有人能演示一下如何检查文件中的重复行,并将任何重复的行删除,覆盖现有文件或创建一个新文件并去除重复的行吗?


@Felice Pollano 不是的,除非我是一个28岁的学生 :D - Michael
1
好的,但无论如何你都在寻求完成的工作... - Felice Pollano
5个回答

10

如果你使用的是.NET4,那么你可以结合使用File.ReadLinesFile.WriteAllLines

var previousLines = new HashSet<string>();

File.WriteAllLines(destinationPath, File.ReadLines(sourcePath)
                                        .Where(line => previousLines.Add(line)));

这个函数的工作方式与LINQ的Distinct方法基本相同,但有一个重要区别: Distinct的输出顺序不能保证与输入序列相同。 显式使用HashSet<T>可以提供此保证。


HashSet<T> 不保留插入顺序。我的意思是,有时它似乎会这样做,但不能保证。您可以在此处阅读 https://learn.microsoft.com/it-it/dotnet/api/system.collections.generic.hashset-1?view=net-5.0 - Mauro Sampietro

2
File.WriteAllLines(topath, File.ReadAllLines(frompath).Distinct().ToArray());

编辑:修改为在 .net 3.5 中工作


2
// Requires .NET 3.5
private void RemoveDuplicate(string sourceFilePath, string destinationFilePath)
{
    var readLines = File.ReadAllLines(sourceFilePath, Encoding.Default);

    File.WriteAllLines(destinationFilePath, readLines.Distinct().ToArray(), Encoding.Default);
}

1

伪代码:

open file reading only

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

for each line in the file:
    if(!list.contains(line)):
        list.append(line)

close file
open file for writing

for each string in list:
    file.write(string);

1

我们要处理多大的文件?

一种策略是逐行读取并将其加载到数据结构中,您可以轻松地检查其中是否存在项目,例如Hashset<int>。我知道我可以使用GetHashCode()可靠地哈希文件的每个字符串行(用于内部检查字符串相等性-这就是我们想要确定重复项的内容),然后只需检查已知的哈希值即可。所以,类似于以下内容:

var known = new Hashset<int>();
using (var dupe_free = new StreamWriter(@"c:\path\to\dupe_free.txt"))
{
    foreach(var line in File.ReadLines(@"c:\path\to\has_dupes.txt")
    {
        var hash = line.GetHashCode();
        if (!known.Contains(hash)) 
        {
            known.Add(hash);
            dupe_free.Write(line);
        }
    }
}

或者,您可以利用 Linq 的 Distinct() 方法,在一行中完成,就像 Blindy 建议的那样:

File.WriteAllLines(@"c:\path\to\dupe_free.txt", File.ReadAllLines((@"c:\path\to\has_dupes.txt").Distinct().ToArray());

@LukeH 对的,这就是为什么我的主要答案是手写循环读取和写入它们;哈希集是一种廉价的查找方式,并且使用gethashcode可以保证正确的顺序和唯一性。 - Factor Mystic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接