0
  • Both lists have Objects with ID and Name properties.

    1. List1({1, apple}, {2, orange}, {3, banana}, {4, potato}, {5, tomato})
    2. List2({1, apple}, {2, orange}, {3, banana})
  • Final output List3({4, potato}, {5, tomato})

Avi
  • 73
  • 1
  • 2
  • 6
  • 2
    Possible duplicate of [Use LINQ to get items in one List<>, that are not in another List<>](http://stackoverflow.com/questions/3944803/use-linq-to-get-items-in-one-list-that-are-not-in-another-list) – C4d Mar 29 '17 at 14:00
  • I'd concat both together and group them. – Werner Mar 29 '17 at 14:01
  • If List2 also contains, for example, {6, pineapple}, should the final list then contain ({4, potato}, {5, tomato}, {6, pineapple}) or ({4, potato}, {5, tomato})? – PJvG Mar 29 '17 at 14:17
  • Expected: ({4, potato},{5, tomato}) – Avi Mar 31 '17 at 20:00

4 Answers4

6

Following idea:

  1. Build intersection set
  2. Remove intersection set from base lists

    IEnumerable<int> common = a.Intersect(b).ToList();
    
    a.RemoveAll(x => common.Contains(x));
    b.RemoveAll(x => common.Contains(x));
    
gartenkralle
  • 646
  • 1
  • 11
  • 21
2

This example doesn't contain objects but it should show you a way to do what you are trying to achieve

var list1 = new List<string>{"apple", "orange", "banana", "potato", "tomato"};
var list2 = new List<string>{"apple", "orange", "banana"};
var result = list1.Where(f => !list2.Contains(f));
Rajdeep Dosanjh
  • 1,157
  • 1
  • 9
  • 20
0

You're looking for a symmetric difference

Dictionary<int, string> fruit = new Dictionary<int, string>() { { 1, "apple" }, { 2, "orange" }, { 3, "banana" }, { 4, "potato" }, { 5, "tomato" } };
Dictionary<int, string> fruit2 = new Dictionary<int, string>() { { 1, "apple" }, { 2, "orange" }, { 3, "banana" } };
var result = fruit.Values.Concat(fruit2.Values).Except(fruit.Values.Intersect(fruit2.Values));

I'm not sure if it makes sense to to keep up the ID because there could also be the case

List1({1, apple} and List2({1, potato}

fubo
  • 44,811
  • 17
  • 103
  • 137
0
IEnumerable<T> list3 = list1.Except(list2);

This works if your objects in the two lists are the same (the same object reference). If they are only equal, but not the same, consider overriding the Equals operator of the type of the objects in your sets, or use an alternative LINQ expression, such as

IEnumerable<TypeWithId> set3 = set1.Where((item) => !set2.Any((item2) => item.id==item2.id));
cmonsqpr
  • 583
  • 6
  • 13