Home > Net >  Get all invalid from a list LINQ
Get all invalid from a list LINQ

Time:08-20

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

CodePudding user response:

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

CodePudding user response:

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