Here we will see how we can find the difference between two lists in C# using LINQ.
Suppose you have two lists of elements lstA and lstB declared as:
List<string> lstA = new List<string> { "A", "B", "C", "D","G" }; List<string> lstB = new List<string> { "A", "B", "C", "D","F" };
Using Except extension method
Here we are interested in finding the difference between the two lists.Here we can use the Except extension method.This method returns the items which are there in the first collection but not there in the second collection.
So if are interested in only finding the items which are there in the first list but not in the second list then you can use the Except method as:
var difference=lstA.Except(lstB).ToList();
Above will return the alphabet “G”
But if you are only interested in finding the difference between the lists then you can use the following
List<string> difference = new List<string>(); if(lstA.Count()>lstB.Count()) difference=lstA.Except(lstB).ToList(); else difference=lstB.Except(lstA).ToList();
Using Where extension method
You can also use the where method to find elements which are in the first list but not in second list:
var difference= lstA.Where(p =>!lstB.Contains(p));
Leave a Reply