首页 > 后端开发 > C++ > LINQ 的 `Contains()` 方法如何替换 `WHERE IN` 子句?

LINQ 的 `Contains()` 方法如何替换 `WHERE IN` 子句?

DDD
发布: 2025-01-06 17:53:43
原创
1016 人浏览过

How Can LINQ's `Contains()` Method Replace a `WHERE IN` Clause?

LINQ 中的Where IN 子句

使用数据库时,您可能会遇到需要使用 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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板