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

Time:11-03

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();

CodePudding user response:

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();

CodePudding user response:

You need to filter by where your Role-list contains the job profile role:

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

...or in fluent:

var records = db.JobProfiles
    .Where(x => Roles.Contains(x.Role))
    .ToList();
  • Related