LINQ中IN子句的位置

如何在SQL Server中创build一个类似于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; } 

这个expression应该做你想达到的。

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

这将转化为LINQ to SQL中的where子句…

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

我喜欢它作为扩展方法:

 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。

“IN”子句通过.Contains()方法构build到linq中。

例如,要获得所有具有“NY”或“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(); } 
 from state in _objedatasource.StateList() where listofcountrycodes.Contains(state.CountryCode) select state 
 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>(); } } 

这个有点不同的想法。 但它对你有用。 我已经使用子查询到linq主查询中。

问题:

假设我们有文档表。 架构如下架构: 文件(名称,版本,auther,修改date)复合键:名称,版本

所以我们需要获得所有文件的最新版本。

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