Get distinct list between two lists in C#

kartal picture kartal · Jul 12, 2011 · Viewed 36k times · Source

I have two lists of strings. How do I get the list of distinct values between them or remove the second list elements from the first list?

List<string> list1 = { "see","you","live"}

List<string> list2 = { "see"}

The result should be {"you","live"}.

Answer

Justin Niessner picture Justin Niessner · Jul 12, 2011

It looks to me like you need Enumerable.Except():

var differences = list1.Except(list2);

And then you can loop through the differences:

foreach(var difference in differences)
{
    // work with each individual string here.
}