tags:

views:

1256

answers:

4

How to make a where in clause similar to one in SQL Server?

I made one by myself but can anyone please improve this?

    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;
    }
+1  A: 

This will translate to a where in clause in Linq to SQL...

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));

In the case of your query, you could do something like this...

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});
Scott Ivey
+4  A: 

This expression should do what you want to achiev.

dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))
Daniel Brückner
+1  A: 
from state in _objedatasource.StateList()
where listofcountrycodes.Contains(state.CountryCode)
select state
Andrija
+2  A: 

The "IN" clause is built into linq via the .Contains() method.

For example, to get all People whose .States's are "NY" or "FL":

using (DataContext dc = new DataContext("connectionstring")){
List<string> states = new List<string>(){"NY", "FL"};
List<Person> list = (from p in dc.GetTable<Person>() where states.Contains(p.State) select p).ToList();

}

nikmd23