C# 比较两个文本文件,并导出不带';t存在于文件1中
基本上我需要做的是:C# 比较两个文本文件,并导出不带';t存在于文件1中,c#,text,C#,Text,基本上我需要做的是: File no.1: 1 2 4 5 51 21 File no.2: 31 21 4 What should be exported: 1 2 5 51 基本上只导出第二个文本中不存在的行 我目前的尝试: bool exists = false; string[] lines1 = File.ReadAllLines("path1"); string[] lines2 = File.ReadAllLines("path2"); fo
File no.1:
1
2
4
5
51
21
File no.2:
31
21
4
What should be exported:
1
2
5
51
基本上只导出第二个文本中不存在的行
我目前的尝试:
bool exists = false;
string[] lines1 = File.ReadAllLines("path1");
string[] lines2 = File.ReadAllLines("path2");
for (int i = 0; i < lines1.Length; i++)
{
for (int g = 0; g < lines2.Length; g++)
{
if (lines1[i] == lines2[g])
{
exists = true;
Console.WriteLine("Exists!");
break;
}
}
if (!exists)
{
Console.WriteLine(lines1[i]);
exists = false;
}
}
Console.WriteLine("End of file reached");
Console.ReadLine();
bool exists=false;
string[]lines1=File.ReadAllLines(“路径1”);
字符串[]lines2=File.ReadAllLines(“路径2”);
对于(int i=0;i
我觉得有一个合适的功能供我使用,虽然这是我想出的,谢谢你的帮助 根据您想要的结果,您可以使用LINQ和扩展方法。像这样:
string[] result = lines1.Except(lines2).ToArray();
根据您想要的结果,您可以使用LINQ和扩展方法。像这样:
string[] result = lines1.Except(lines2).ToArray();
一般情况下,如果
file2
可以包含要保留的重复项,我建议使用HashSet
:
HashSet-toSkip=新的HashSet(File.ReadLines(path1));
var toExport=File
.ReadLines(路径2)
其中(行=>!toSkip.Contains(行));
//.ToArray();// 一般情况下,如果file2
可以包含要保留的重复项,我建议使用HashSet
:
HashSet-toSkip=新的HashSet(File.ReadLines(path1));
var toExport=File
.ReadLines(路径2)
其中(行=>!toSkip.Contains(行));
//.ToArray();//哇!好吧,这让我的尝试很可悲。非常感谢,祝您度过愉快的一天:)通过使用file.ReadLines
而不是file.ReadAllLines
读取源文件字符串数组,可以改进此解决方案。哇!好吧,这让我的尝试很可悲。非常感谢,祝您度过愉快的一天:)通过使用file.ReadLines
而不是file.ReadAllLines
读取源文件字符串数组,可以改进此解决方案。您确定不希望结果中也包含5吗?@FrancescoB。哈哈!你是对的,那是我的错:)你确定你不想在结果中也得到5分吗?@FrancescoB。哈哈!你是对的,那是我的错:)