在LINQ(查询语法)中,我可以有多个发件人。
据我所读:
“查询表达式可以包含子查询,这些子查询也以from子句开头...”
来源:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/from-clause
但是,化合物来源(使用多个来源)和子查询之间有什么区别?的化合物示例如下:
List<A> persons = new List<A>();
var query = from mychild in persons
from ch in mychild.Children
from c in ch.Children
select c;
还是第二行“来自ch in ..”作为第一行的子查询(来自mychild),第三行“来自c”是针对ch的子查询?子查询中所有子查询的名称都来自“ compound from”?
答案 0 :(得分:1)
每个查询语法查询必须以select
表达式结尾。这是区分子查询的方式。如果您要解释:
from c in ch.Children
select c;
作为子查询,则查询为:
var query = from mychild in persons
from ch in mychild.Children
(from c in ch.Children
select c);
和外部查询:
from mychild in persons
from ch in mychild.Children
没有select
表达式。
此外,如果这是一个子查询,它将只是将查询粘贴到from
语句的末尾,而不描述其用法。为了使其包含在外部查询中,需要以某种方式使用。要将Children
的查询作为子查询,您可以执行以下操作:
var query = from mychild in persons
from ch in mychild.Children
from outerChild in
(from innerChild in ch.Children
select innerChild)
select outerChild;
很显然,这不是使用子查询的有用方法,但这就是将其解释为子查询所需要的转换类型。
是的,只需计算select
个关键字的数量即可查看查询的数量。
答案 1 :(得分:0)
复合from子句是当您从外部查询访问内部元素时。否则,您可以定义在其他数据源上运行的子查询。
考虑以下示例:
var somePersons = new List<Person>
{
new Person { Names = new List<string> { "John", "Smith" } },
new Person { Names = new List<string> { "Mike", "Soandso" } }
};
var otherPersons = new List<Person>
{
new Person { Names = new List<string> { "Jane", "Doe" } },
new Person { Names = new List<string> { "Sarah", "Connor" } }
};
var query = from person1 in somePersons
from name1 in person1.Names
from person2 in otherPersons
from name2 in person2.Names
select new Person { Names = new List<string> { name1, name2 } };
答案 2 :(得分:0)
此构造转换为.SelectMany
。可用于向下导航一对多关系。
var query =
from customer in customers
from order in customer.Orders
select order;
此构造会生成一个子查询。
DateTime today = DateTime.Today;
var query =
from customer in customers
let orderCount = (
from order in customer.Orders
where order.ShipDate == today
select order).Count()
select new {customer, orderCount};