LINQ到实体加盟VS群组加入
我有搜索网站,但我仍然无法找到一个简单的答案。有人可以请解释(以简单的英语)什么是群组加入
是?它是如何从一个普通的内不同的加入
?它是常用的?难道只为方法的语法?怎么样查询语法?一个C#code例子是好的。
I have web searched but I still cant find a simple answer. Can someone please explain (in simple English) what a GroupJoin
is? How is it different from a regular inner Join
? Is it commonly used? Is it only for method syntax? What about query syntax? A c# code example would be nice.
假设你有两个列表:
Id Value
1 A
2 B
3 C
Id ChildValue
1 a1
1 a2
1 a3
2 b1
2 b2
在 加入
在编号
字段两个名单,结果将是
When you Join
the two lists on the Id
field the result will be:
Value ChildValue
A a1
A a2
A a3
B b1
B b2
在 群组加入
在编号
字段两个名单,结果将是
When you GroupJoin
the two lists on the Id
field the result will be:
Value ChildValues
A [a1, a2, a3]
B [b1, b2]
C []
所以加入
产生的父母子女价值观的平面(表格)的结果。结果群组加入
产生条目的第一个列表的列表,每个在第二个列表中的组加入条目。
So Join
produces a flat (tabular) result of parent and child values.GroupJoin
produces a list of entries in the first list, each with a group of joined entries in the second list.
这就是为什么加入
是 INNER JOIN
在SQL等价:对于 C 。而群组加入
是 OUTER相当于JOIN
: C
是在结果集中,但随着相关条目的空列表(在SQL结果集将有一排ç - 空
)。
That's why Join
is the equivalent of INNER JOIN
in SQL: there are no entries for C
. While GroupJoin
is the equivalent of OUTER JOIN
: C
is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null
).
这是一种方法,指出了一个全球性的方式上存在差异,因为寻找到的语法是直接总有种困惑。但现在我们已经准备好语法的详细信息。
This was a way to point out the differences in a global way, because looking into the syntax directly is always kind of confusing. But now we're ready for syntax details.
因此,让两个列表是的IEnumerable<家长和GT;
和的IEnumerable<儿童>
分别。 (在LINQ的情况下实体:的IQueryable< T>
)。
So let the two lists be IEnumerable<Parent>
and IEnumerable<Child>
respectively. (In case of Linq to Entities: IQueryable<T>
).
加入
语法将
Join
syntax would be
from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }
返回一个的IEnumerable&LT; X&GT;
其中X是一个匿名类型有两个属性,值
和 ChildValue
。此COM prehension语法使用 加入
引擎盖下的方法。
returning an IEnumerable<X>
where X is an anonymous type with two properties, Value
and ChildValue
. This comprehension syntax uses the Join
method under the hood.
群组加入
语法将
GroupJoin
syntax would be
from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }
返回一个的IEnumerable&LT; Y&GT;
Y是一个匿名类型包括类型的一个属性父
和物业类型的IEnumerable&LT;儿童&GT;
。此COM prehension语法使用 群组加入
引擎盖下的方法。
returning an IEnumerable<Y>
where Y is an anonymous type consisting of one property of type Parent
and a property of type IEnumerable<Child>
. This comprehension syntax uses the GroupJoin
method under the hood.
我们可能只是做选择G以
在后者的查询,这将选择的IEnumerable&LT; IEnumerable的&LT;儿童&GT;&GT;
,说列表的列表。在许多情况下与父选择包括的是更为有用。
We could just do select g
in the latter query, which would select an IEnumerable<IEnumerable<Child>>
, say a list of lists. In many cases the select with the parent included is more useful.