Search code examples
c#linqexcept

Get all invalid from a list LINQ


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();

Solution

  • 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();