C# 选择 Linq 中的所有子对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1009455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting all child objects in Linq
提问by Shaul Behr
This really should be easy, but I just can't work it out myself, the interface is not intuitive enough... :(
这真的应该很容易,但我自己无法解决,界面不够直观...... :(
Let's say I have a State
table, and I want to select all Counties
from multiple States
. In SQL that would be:
假设我有一张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
The above example is trivial enough to convert to Linq in a static context:
上面的例子很简单,可以在静态上下文中转换为 Linq:
var q = MyDataContext.GetTable<County>().Where(c => c.State.TimeZone = -5);
But where it starts getting complicated is if I want a more context sensitive query, such as the following:
但它开始变得复杂的是,如果我想要一个更上下文敏感的查询,例如以下内容:
public static List<County> GetCountiesForStates(List<State> states) {
// gotta do something to return all the counties for all these states
}
Now I could do something like this inside that method:
现在我可以在那个方法中做这样的事情:
var q = MyDataContext.GetTable<County>().Where(c => states.Contains(c.State));
but IMO that is really inelegant, because (a) I have to get a static MyDataContext
instead of using the implicit data context of the State objects and (b) you're working backwards, and if you start complicating the query further it gets even uglier.
但是 IMO 真的很不优雅,因为 (a) 我必须得到一个静态的MyDataContext
而不是使用 State 对象的隐式数据上下文,并且 (b) 你在向后工作,如果你开始进一步使查询复杂化,它会变得更加丑陋.
Is there a way of starting the query with:
有没有办法开始查询:
var q = states... // or "from s in states..."
Instinctively, I want to believe you can do this, but I haven't yet found the way...
本能地,我想相信你能做到这一点,但我还没有找到方法......
采纳答案by eulerfx
You can do this:
你可以这样做:
var q = from c in countries
from s in c.States
where c.Property == Something
select s;
This will give you an enumeration of all states within all countries. This translates into the following:
这将为您提供所有国家/地区内所有州的枚举。这转化为以下内容:
var q = countries.Where(x => c.Property == Something).SelectMany(c => c.States);