Linq To Entities: String.Contains a list [duplicate]
Asked Answered
A

1

1

I am using ASP.net Core 3.0 with Entity Framework Core 3.0 and Pomelo.EntityFrameworkCore provider for MySQL, I need to query all the users that are from specific Towns. Lets say for example I have a list of strings called targettedTowns in which I have the following towns

var targettedTowns = new List<string>() {"korangi","landhi","zia colony","shah faisal","quaidabad"};
  • korangi
  • landhi
  • zia colony
  • shah faisal
  • quaidabad

Now I want to find all the users that are located in the targettedTowns list using Linq Lambda syntax.

Users in my database have their towns saved like

  • Korangi
  • Korangi-Zia Colony
  • Korangi-Bhittai Colony
  • Korangi-Allah Wala Town
  • Landhi-Sherpao
  • Landhi-Awami Colony
  • Landhi-Sherabad
  • ShahFaisal

What I am trying currently is

var users = context.Users.Where(x => x.Town.ToLower().Contains(targettedList)).ToList();

but as String.Contains does not take a list in argument so I cant use this.

Aixenprovence answered 29/3, 2020 at 13:27 Comment(1)
P
0

You just need to replace x.Town.ToLower() with targettedList in where condition:

var users = context.Users.Where(x => targettedList.Contains(x.Town)).ToList();
Polysyllabic answered 29/3, 2020 at 13:33 Comment(2)
That only brings the exact matches and users with Town korangi-Bhittai Colony would not be found using thisAixenprovence
Ccould you please post the translated tsql of above linq query.Polysyllabic

© 2022 - 2024 — McMap. All rights reserved.