-1

I have two lists that I have a property that I want to compare on. Based on this property, I want to return all the elements from list1 that is not in list2.

List1: {Name, Age, Id}

{John, 10, 1},
{Joe, 20, 2},
{Mary, 30, 3}

List2: {Name, Age, Id}

{John, 10, 1}
{Joe, 20, 2}
{Mary, 30, 5}

This should only return from list 1

{Mary, 30, 3}

I've tried

var invalidElements = list1
                .Select(o => list2.Any(p => p.Id != o.Id))
                .ToList();
Jim G.
  • 15,141
  • 22
  • 103
  • 166
  • Does this answer your question? [Linq find differences in two lists](https://stackoverflow.com/questions/2404301/linq-find-differences-in-two-lists) – Jim G. Aug 19 '22 at 17:45
  • 1
    Does this answer your question? "[Compare two list of objects and select common and difference records based some property](/q/9926091/90527)", "[compare properties in classes of list in class](/q/18742293/90527)", "[C# Find difference of two custom object lists based only on some properties](/q/44554700/90527)" – outis Aug 20 '22 at 18:26
  • … "[Get the differences between 2 lists](/q/10810438/90527)", "[LINQ expression to get difference from 2 list with a property](/q/31828664/90527)", "[Comparing 2 lists and return difference in a 3rd list](/q/33752401/90527)" – outis Aug 20 '22 at 18:31
  • 1
    As per the [site guidelines](/help/how-to-ask) in the [help], please [search](/help/searching) before posting. See also "[How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/90527)" – outis Aug 20 '22 at 18:36

2 Answers2

2

Use the Where method instead of select (and invert your logic). Select is used to project your collection to another of a different type (often a property of your element).

var invalidElements = list1
                .Where(o => !list2.Any(p => p.Id == o.Id))
                .ToList();
Luke
  • 743
  • 6
  • 20
1

Because you wrote that you want to filter by Id, you can use the new ExceptBy method:

var invalidElements = list1.ExceptBy(list2.Select(a => a.Id), x => x.Id);
A.B.
  • 2,374
  • 3
  • 24
  • 40