Sha*_*ica 9 c# linq linq-to-sql
这真的应该很容易,但我不能自己解决,界面不够直观...... :(
假设我有一张State
桌子,我想Counties
从多个中选择全部States
.在SQL中将是:
select c.*
from State s join County c on c.StateCode = s.StateCode
where s.TimeZone = -5 -- or some other criteria
Run Code Online (Sandbox Code Playgroud)
上面的例子非常简单,可以在静态上下文中转换为Linq:
var q = MyDataContext.GetTable<County>().Where(c => c.State.TimeZone = -5);
Run Code Online (Sandbox Code Playgroud)
但是,如果我想要一个更加上下文敏感的查询,例如以下内容:
public static List<County> GetCountiesForStates(List<State> states) {
// gotta do something to return all the counties for all these states
}
Run Code Online (Sandbox Code Playgroud)
现在,我可以在该方法中执行类似的操作:
var q = MyDataContext.GetTable<County>().Where(c => states.Contains(c.State));
Run Code Online (Sandbox Code Playgroud)
但IMO非常不优雅,因为(a)我必须得到一个静态MyDataContext
而不是使用State对象的隐式数据上下文,(b)你正在向后工作,如果你开始使查询复杂化,它甚至会变得更加丑陋.
有没有办法启动查询:
var q = states... // or "from s in states..."
Run Code Online (Sandbox Code Playgroud)
本能地,我想相信你可以做到这一点,但我还没有找到方法......
eul*_*rfx 32
你可以这样做:
var q = from c in countries
from s in c.States
where c.Property == Something
select s;
Run Code Online (Sandbox Code Playgroud)
这将为您提供所有国家/地区内所有州的列举.这转化为以下内容:
var q = countries.Where(x => c.Property == Something).SelectMany(c => c.States);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15538 次 |
最近记录: |