29

I had create a two int type list and assign the items that are only in list1 to list1 using except method. for eg

List<int> list1 = new List<int>();
List<int> list2 = new List<int>();

list1 = {1,2,3,4,5,6} // get items from the database
list2 = {3,5,6,7,8}   // get items from the database

list1 = list1.Except(list2); // gives me an error.

Please give me suggestion. What is the right way to do it.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Lakhae
  • 1,809
  • 5
  • 25
  • 40

1 Answers1

75

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

raddevus
  • 8,142
  • 7
  • 66
  • 87
Michal Klouda
  • 14,263
  • 7
  • 53
  • 77