How To Select Multiple Records using the List of Id’s with LINQ? Entity Framework

It is not a rare situation when it is necessary to make a selection of elements from the database based on the list of IDs. You can use the ‘Where‘ method in LINQ and ‘Contains‘ in List to filter your data based on the list of Id’s. Here’s an example:

using (var yarkulDbContext = new YarkulDbContext(PersonManager.dbOptions) { })
    var myPersonIdsList = new List<int>() { 2, 3, 4 };
    var persons = yarkulDbContext.
        Where(p => myPersonIdsList.Contains(p.Id))

The key line is: .Where(p => myPersonIdsList.Contains(p.Id)), check the next screenshot for more details:

C# linq select ids from list example

You can see that behind-the-scenes LINQ expression transformed to the ‘WHERE [p].[Id] IN (2,3,4)‘ statement. Remember that it works fine for small data sets.

My artifacts for this article are:

  • Visual Studio 2022
  • .Net 6.0
  • MS SQL 2019 Express

You may also be interested to read my articles related to Entity Framework:

Leave a Comment