选择Linq中的所有子对象

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)

  • 只是一个小错字 - 应该是"countries.Where(c => c.Property)等... (3认同)
  • 这个答案有点令人困惑,因为它涉及"国家"而OP涉及"县".因此,层次结构是相反的. (2认同)