Categories
.NET Core

LINQ: Where Not In Another List

This is a short post on how to filter items from one list based on items on another list. We will use .NET Linq for writing the query syntax implementing where not in another list scenario.

Problem Introduction

Let’s say we have two lists as below:

List<Post> skipPosts = new List<Post>();
skipPosts.Add(new Post() { ID = 1 });
skipPosts.Add(new Post() { ID = 2 });
skipPosts.Add(new Post() { ID = 5 });

List<Post> posts = new List<Post>();
posts.Add(new Post() { ID = 1 });
posts.Add(new Post() { ID = 2 });
posts.Add(new Post() { ID = 3 });
posts.Add(new Post() { ID = 4 });
posts.Add(new Post() { ID = 5 });

The posts list is our main list from where we want to filter out the posts that are in skipPosts list.

Solution With Linq To Compare Two Lists

The simplest solution with Linq:

var result = posts.Where(p => !skipPosts.Any(p2 => p2.ID == p.ID));

This solution is a short and quite effective with smaller data sets.

If you are working with really large datasets then you might have to consider other options as well.