我有两个文本文件 (TXT),其中包含超过 200 万个不同的文件名。我想遍历第一个文件中的所有名称,并找到第二个文本文件中也存在的名称。
我已经尝试循环遍历 StreamReader
但它需要很多时间。我也尝试了下面的代码,但仍然需要太多时间。
StreamReader first = new StreamReader(path);
string strFirst = first.ReadToEnd();
string[] strarrFirst = strFirst.Split('\n');
bool found = false;
StreamReader second = new StreamReader(path2);
string str = second.ReadToEnd();
string[] strarrSecond = str.Split('\n');
for (int j = 0; j < (strarrFirst.Length); j++)
{
found = false;
for (int i = 0; i < (strarrSecond .Length); i++)
{
if (strarrFirst[j] == strarrSecond[i])
{
found = true;
break;
}
}
if (!found)
{
Console.WriteLine(strarrFirst[j]);
}
}
比较文件的好方法是什么?
最佳答案
这个怎么样:
var commonNames = File.ReadLines(path).Intersect(File.ReadLines(path2));
这是 O(N + M) 而不是您当前的解决方案,它测试第一个文件中的 every 行和第二个文件中的 every 行 - O(N * M ).
假设您使用的是 .NET 4。否则,您可以使用 File.ReadAllLines
,但这会将整个文件读入内存。或者你可以写出相当于 File.ReadLines
的东西你自己 - 这并不难。
最终,当您摆脱当前代码中的 O(N * M) 问题时,您可能会受到文件 IO 的限制 - 没有太多方法可以解决这个问题。
编辑:对于 .NET 2,首先让我们实现类似 ReadLines
的东西:
public static IEnumerable<string> ReadLines(string file)
{
using (TextReader reader = File.OpenText(file))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
现在我们真的想要使用 HashSet<T>
,但这不在 .NET 2 中 - 所以让我们使用 Dictionary<TKey, TValue>
相反:
Dictionary<string, string> map = new Dictionary<string, string>();
foreach (string line in ReadLines(path))
{
map[line] = line;
}
List<string> intersection = new List<string>();
foreach (string line in ReadLines(path2))
{
if (map.ContainsKey(line))
{
intersection.Add(line);
}
}
关于c# - 如何循环比较两个文本文件中的数百万个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7497877/