-2

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.

Ziad Akiki
  • 2,601
  • 2
  • 26
  • 41
  • Or you can just scan the lines after and add the duplicates yourself. Something like if (line(i + 1) == line(i)) onlyB.add(line(i)) – tomashauser May 02 '20 at 20:06
  • DIFF is HARD - Depending on the details of your requirements this may be well beyond any simple solution. For a sobering example see [here](https://stackoverflow.com/questions/24887238/how-to-compare-two-rich-text-box-contents-and-highlight-the-characters-that-are/24970638?r=SearchResults&s=1|27.1920#24970638) – TaW May 02 '20 at 20:36
  • Why is `bbb`not included in the diff? its only included in the first file. – RoadRunner May 02 '20 at 21:21
  • Try to express the exact rules of what you're trying to achieve. There's a good chance that after that, you'll be able to do it. At least it would help us help you. – Gert Arnold May 03 '20 at 13:22

1 Answers1

0

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
Rahul
  • 76,197
  • 13
  • 71
  • 125