当您使用string.Split
LINQTake
和SequenceEqual
.
bool AnyDifferent(string file1FullText, string file2FullText)
{
string[] file1Lines = file1FullText.Split('\n');
string[] file2Lines = file2FullText.Split('\n');
if (file1Lines.Length != file2Lines.Length)
return true;
for (int i = 0; i < file1Lines.Length; i++)
{
var file1LineSplit = file1Lines[i].Split('|');
var file2LineSplit = file2Lines[i].Split('|');
if (!file1LineSplit.Take(2).SequenceEqual(file2LineSplit.Take(2)))
return true;
}
return false;
}
编辑或使用File.ReadLines
以提高性能(您不必在开始比较之前读取整个文件):
bool AnyDifferent(string file1Path, string file2Path)
{
using (var file1Enumerator = File.ReadLines(file1Path).GetEnumerator())
using (var file2Enumerator = File.ReadLines(file2Path).GetEnumerator())
{
while (true)
{
bool result1 = file1Enumerator.MoveNext();
bool result2 = file2Enumerator.MoveNext();
if (result1 != result2)
return true;
else if (!result1 && !result2)
return false;
var file1LineSplit = file1Enumerator.Current.Split('|');
var file2LineSplit = file2Enumerator.Current.Split('|');
if (!file1LineSplit.Take(2).SequenceEqual(file2LineSplit.Take(2)))
return true;
}
}
}