使用数据库时,您可能会遇到需要使用 WHERE IN 子句基于多个条件过滤结果的情况。这可以使用 Contains() 方法在 LINQ(语言集成查询)中轻松实现。
为了说明这一点,假设您要检索属于特定国家/地区代码列表的所有州。您可以使用 Contains() 方法简化此过程,而不是像原始代码中那样手动拆分国家/地区代码并循环它们:
public List<State> Wherein(string listofcountrycodes) { string[] countrycode = null; countrycode = listofcountrycodes.Split(','); List<State> statelist = new List<State>(); for (int i = 0; i < countrycode.Length; i++) { _states.AddRange( from states in _objdatasources.StateList() where states.CountryCode == countrycode[i].ToString() select new State { StateName = states.StateName }); } return _states; }
您可以使用 Contains() 方法简化此过程:
dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))
此表达式检索其国家/地区代码出现在countryCodes集合中的所有州。对于符合指定条件的每个州,lambda 表达式 (s => CountryCodes.Contains(s.CountryCode)) 的计算结果为 true,从而允许您相应地过滤结果。
以上是LINQ 的 `Contains()` 方法如何替换 `WHERE IN` 子句?的详细内容。更多信息请关注PHP中文网其他相关文章!