猿问

LINQ中的IN子句

如何在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;

    }


慕桂英546537
浏览 620回答 3
3回答

子衿沉夜

这个表达式应该做你想要达到的目标。dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))

慕容708150

这将转换为Linq to SQL中的where in子句...var myInClause = new string[] {"One", "Two", "Three"};var results = from x in MyTable&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; where myInClause.Contains(x.SomeColumn)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select x;// ORvar results = MyTable.Where(x => myInClause.Contains(x.SomeColumn));在您的查询的情况下,您可以做这样的事情......var results = from states in _objectdatasource.StateList()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; where listofcountrycodes.Contains(states.CountryCode)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select new State&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; StateName = states.StateName&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };// ORvar results = _objectdatasource.StateList()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Where(s => listofcountrycodes.Contains(s.CountryCode))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(s => new State { StateName = s.StateName});

泛舟湖上清波郎朗

我喜欢它作为扩展方法:public static bool In<T>(this T source, params T[] list){&nbsp; &nbsp; return list.Contains(source);}现在你打电话:var states = _objdatasources.StateList().Where(s => s.In(countrycodes));您也可以传递单个值:var states = tooManyStates.Where(s => s.In("x", "y", "z"));感觉更自然,更接近sql。
随时随地看视频慕课网APP
我要回答