C# – Compare List1 with List2, Return Differences

email me

Text file saved as list1.txt:

alpha
bravo
charlie
delta
echo
foxtrot
golf
hotel
india
juliet
kilo
lima
mike
november
oscar
papa
quebec
romeo
sierra
tango
uniform
victor
whiskey
x-ray
yankee
zulu

Text file saved as list2.txt:

alpha
bravo
charlie
delta
echo
foxtrot
golf
hotel
india
juliet
kilo
lima
mike
november
oscar
papa
romeo
sierra
tango
uniform
victor
whiskey
x-ray
yankee
zulu

 

Code

* tested in Visual Studio 2019

// MrNetTek
// eddiejackson.net/blog
// 1/8/2020
// free for public use
// free to claim as your own

using System;                      // Console
using System.Collections.Generic;  // IEnumerable
using System.Linq;                 // IEnumerable

namespace CompareTwoLists
{
class CompareTwoLists
{
static void Main()
{
// instantiate data sources
string[] list1 = System.IO.File.ReadAllLines(@"C:\csharp\compare_lists\list1.txt");
string[] list2 = System.IO.File.ReadAllLines(@"C:\csharp\compare_lists\list2.txt");

// create the search query
IEnumerable<string> differenceQuery =
list1.Except(list2);

// run the search query
Console.WriteLine("In list1, but not list2:");
foreach (string s in differenceQuery)
// return differences
Console.WriteLine(s);

Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
Environment.Exit(0);

}
}
}

Output

In list1, but not list2:
quebec

Press any key to continue…

 

Notes

File.ReadAllLines()

IEnumerable Interface()

foreach statement

 

tags: C# Lists, C# Comparison, MrNetTek