How to use Except method in list in c#

The Except method returns IEnumerable, you need to convert the result to list:

list1 = list1.Except(list2).ToList();

Here’s a complete example:

List<String> origItems = new List<String>();
    origItems.Add("abc");
    origItems.Add("def");
    origItems.Add("ghi");
    
    List<String> newItems = new List<String>();
    newItems.Add("abc");
    newItems.Add("def");
    newItems.Add("super");
    newItems.Add("extra");
    
    List<String> itemsOnlyInNew = newItems.Except(origItems).ToList();
    foreach (String s in itemsOnlyInNew){
        Console.WriteLine(s);
    }

Since the only items which don’t exist in the origItems are super & extra, The result output is :

super

extra

Leave a Comment