john.1020
john.1020

Reputation: 135

LINQ Select elements of list<T> if list<int> contains any id of list<T>

I'm working on a LINQ query in C# 6. I try to select all elements of a list, if a given list<int> contains any Id of list<T>.

My model class as well as the data structures look like that:

public class Project 
{
   public int ID { get; set; }
   public string Title { get; set; }
}

List<Project> projects = projectService.GetProjects();

List<int> bookmarkIds = new List<int>( new int[] { 1, 4, 7 });

My current LINQ query looks like that:

var bookmarks = projects?.Select(x => bookmarkIds.Any(y => y == x.ID)).ToList();

Unfortunately this query does not work.

Do you know how to select all projects from the projects list, that do have an Id which one can also find in the bookmarkIds list?

Thank you!!

Upvotes: 0

Views: 3943

Answers (1)

NotFound
NotFound

Reputation: 6262

var bookmarks = projects?.Where(x => bookmarkIds.Contains(x.ID)).ToList();

Although in your particular situation you might want to look at using a HashSet to store your bookmark ID's (assuming their order doesn't matter). Those are perfectly suited to check if an ID exists or not.

Upvotes: 2

Related Questions