I need to compare 2 text files and save the differences in another file.
File 1
aaa
bbb
ccc
File 2
aaa
eee
ccc
ccc
I'm currently using this code:
String directory = @"C:\Users\confronto.txt";
String[] linesA = File.ReadAllLines(Path.Combine(directory, @"C:\Users\pari.txt"));
String[] linesB = File.ReadAllLines(Path.Combine(directory, @"C:\Users\dispari.txt"));
IEnumerable<String> onlyB = linesB.Except(linesA);
but this code doesn't see the double ccc
as a difference, so the confronto.txt
is:
eee
instead of:
eee
ccc
as it should be.
Can you help me? Thank you.
You haven't provided any logic behind why you want that duplicate value. You can try combining both the array and group the result set by string element and take only those where count is either 1 or greater than 2. Something like
public static void Main()
{
string[] file1 = new string[]{"aaa","bbb","ccc"};
string[] file2 = new string[]{"aaa","bbb","ccc","eee","ccc"};
List<string> file = new List<string>(file1);
file.AddRange(file2);
var data = file.GroupBy(x => x)
.Select(x => new {Key = x.Key, Count = x.Count()})
.Where(y => y.Count == 1 || y.Count > 2)
.Select(x => x.Key);
foreach (var item in data)
{
Console.WriteLine(item);
}
}
Which results in
ccc
eee
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.