Search code examples
c#linqentity-framework-core

How to use Contain with multiple values in C#, LINQ to pull record


I am working on .NET 6 application with entity framework core. I am creating record search query using LINQ where I am expecting to receive List of string. No of string values are not fixed and will varies. How I can use List in LINQ contain?

List<string> Roles = new List<string>() { "Business Analyst", "Business Analysis Lead", "Application Support Analyst" };

var records = (from jobProfile in db.JobProfiles
          where jobProfile.Role.Contains(Roles) 
          select jobProfile).ToList();

Solution

  • Something like this:

    var records = (
       from jobProfile in db.JobProfiles
       where jobProfile.Role.Any(r => Roles.Contains(r.Name))
       select jobProfile
    ).ToList();
    

    or with fluent interface:

    var records = 
       db
       .JobProfiles
       .Where(jp => jp.Role.Any(r => Roles.Contains(r.Name)))
       .ToList();
    

    Roles can be any IEnumerable. EF will convert the method call to an IN clause.

    Note that if the source (here db.JobProfiles) stopped being an IQueryable and was instead an IEnumerable, then you would be using an O(n) .Contains call. As long as it's EF you can use an IEnumerable for Roles since .Contains is not actually called in that case, but for LINQ to Objects you would want to make sure that it's a Set of some kind instead.

    If Role is a string property rather than an entity, then it's a bit simpler:

    var records = (
       from jobProfile in db.JobProfiles
       where Roles.Contains(jobProfile.Role)
       select jobProfile
    ).ToList();
    

    or with fluent interface:

    var records = 
       db
       .JobProfiles
       .Where(jp => Roles.Contains(jp.Role))
       .ToList();