2009-06-06 20 views
119

Come creare una clausola where in una simile in SQL Server?Dove clausola IN in LINQ

Ne ho fatto uno da solo ma qualcuno può migliorare questo?

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

risposta

191

Questa espressione dovrebbe fare ciò che si desidera ottenere.

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

questo confronta i valori stringa, ma per quanto riguarda gli ID ?? –

+0

@JitendraPancholi È possibile utilizzare un join per i numeri interi. – Eugene

+0

@JitendraPancholi se si crea un elenco è possibile verificare gli ID. È supportato in .Net 4. Non sono sicuro delle versioni precedenti. –

81

Questo si tradurrà in un dove clausola 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)); 

Nel caso della tua ricerca, si potrebbe fare qualcosa di simile ...

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}); 
+0

Grazie;) Mi ha aiutato anche a +1 –

4
from state in _objedatasource.StateList() 
where listofcountrycodes.Contains(state.CountryCode) 
select state 
6

La clausola "IN" è incorporato in LINQ tramite i .Contains() metodo.

Ad esempio, per ottenere tutte le persone i cui .States di sono "NY" o "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(); 
} 
1
public List<State> GetcountryCodeStates(List<string> countryCodes) 
{ 
    List<State> states = new List<State>(); 
    states = (from a in _objdatasources.StateList.AsEnumerable() 
    where countryCodes.Any(c => c.Contains(a.CountryCode)) 
    select a).ToList(); 
    return states; 
} 
+5

Benvenuti su SO, qui è una buona pratica spiegare perché utilizzare la soluzione e non solo come. Ciò renderà la tua risposta più preziosa e aiuterà ulteriormente il lettore ad avere una migliore comprensione di come lo fai. Suggerisco anche di dare un'occhiata alle nostre FAQ: http://stackoverflow.com/faq. – ForceMagic

2

Questa piccola idea po 'diverso. Ma ti sarà utile. Ho usato la query secondaria all'interno della query principale di linq.

Problema:

diciamo che abbiamo piano di lettura. Schema come segue schema: documento (nome, versione, Auther, ModifiedDate) chiavi composte: nome, versione

Così abbiamo bisogno di ottenere le ultime versioni di tutti i documenti.

soloution

var result = (from t in Context.document 
          where ((from tt in Context.document where t.Name == tt.Name 
           orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version) 
          select t).ToList(); 
22

mi piace come un metodo di estensione:

public static bool In<T>(this T source, params T[] list) 
{ 
    return list.Contains(source); 
} 

Ora si chiamano:

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

È possibile passare valori individuali troppo:

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

Si sente più naturale e più vicino a sql.

+1

dove dovrei scrivere questo metodo di estensione – Rohaan

+0

@Roana, in qualsiasi classe statica (che non è generica e non annidata) – nawfal

+0

C'è solo il chilometraggio nella scrittura della classe di estensione se si sta riutilizzando la parte Dove del proprio linq. Hai messo in svantaggio la risposta, ma volevo solo consentire agli altri che si imbattono in questa domanda e andare direttamente per il percorso del metodo di estensione. – JARRRRG

6
public List<Requirement> listInquiryLogged() 
{ 
    using (DataClassesDataContext dt = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString)) 
    { 
     var inq = new int[] {1683,1684,1685,1686,1687,1688,1688,1689,1690,1691,1692,1693}; 
     var result = from Q in dt.Requirements 
        where inq.Contains(Q.ID) 
        orderby Q.Description 
        select Q; 

     return result.ToList<Requirement>(); 
    } 
}