为了账号安全,请及时绑定邮箱和手机立即绑定

LINQ中的IN子句

LINQ中的IN子句

C#
慕桂英546537 2019-09-20 14:29:32
如何在SQL Server中创建一个类似于where的子句?我自己做了一个,但任何人都可以改进吗?    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;    }
查看完整描述

3 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

这个表达式应该做你想要达到的目标。


dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))


查看完整回答
反对 回复 2019-09-20
?
慕容708150

TA贡献1831条经验 获得超4个赞

这将转换为Linq to SQL中的where in子句...


var myInClause = new string[] {"One", "Two", "Three"};


var results = from x in MyTable

              where myInClause.Contains(x.SomeColumn)

              select x;

// OR

var results = MyTable.Where(x => myInClause.Contains(x.SomeColumn));

在您的查询的情况下,您可以做这样的事情......


var results = from states in _objectdatasource.StateList()

              where listofcountrycodes.Contains(states.CountryCode)

              select new State

              {

                  StateName = states.StateName

              };

// OR

var results = _objectdatasource.StateList()

                  .Where(s => listofcountrycodes.Contains(s.CountryCode))

                  .Select(s => new State { StateName = s.StateName});


查看完整回答
反对 回复 2019-09-20
?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

我喜欢它作为扩展方法:


public static bool In<T>(this T source, params T[] list)

{

    return list.Contains(source);

}

现在你打电话:


var states = _objdatasources.StateList().Where(s => s.In(countrycodes));

您也可以传递单个值:


var states = tooManyStates.Where(s => s.In("x", "y", "z"));

感觉更自然,更接近sql。


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 619 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信