Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading