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

為{幸葍}努か 提交于 2020-04-18 05:43:46

问题


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.


回答1:


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

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


来源:https://stackoverflow.com/questions/60914868/linq-to-entities-string-contains-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!