[英]LINQ, INNER JOIN (Join or GroupJoin)?
I am kind of lost between Join and GroupJoin. 我在Join和GroupJoin之间有点迷路。 Which way is the right way to do INNER JOIN?
进行INNER JOIN的正确方法是哪一种? On one hand Join is doing the right job, but I have to call Distinct.
一方面,Join做得很好,但我必须打电话给Distinct。 On the other hand GroupJoin is grouping by itself, but gives me empty RHS.
另一方面,GroupJoin本身正在分组,但是给了我空的RHS。 Or there is a better way?
还是有更好的方法?
using System;
using System.Linq;
public class Foo
{
public string Name { get; set; }
public Foo(string name)
{
Name = name;
}
}
public class Bar
{
public Foo Foo { get; set; }
public string Name { get; set; }
public Bar(string name, Foo foo)
{
Foo = foo;
Name = name;
}
}
public class Program
{
public static Foo[] foos = new[] { new Foo("a"), new Foo("b"), new Foo("c"), new Foo("d") };
public static Bar[] bars = new[] { new Bar("1", foos[1]), new Bar("2", foos[1]) };
public static void Main(string[] args)
{
#if true
var res = foos.Join(
bars,
f => f,
b => b.Foo,
(f, b) => f
)
.Distinct();
#else
var res = foos.GroupJoin(
bars,
f => f,
b => b.Foo,
(f, b) => new { f, b }
)
.Where(t => t.b.Any())
.Select(t => t.f);
#endif
foreach (var r in res)
Console.WriteLine(r.Name);
}
}
Thanks! 谢谢!
The key to understanding this is to look at the types of the parameters for that last lambda you're passing in. 理解这一点的关键是查看您传入的最后一个lambda的参数类型。
For Join
, the b
will be a single bar
, and you will get a row for every bar
that has a match. 对于
Join
, b
将是单个bar
,并且您将为每个具有匹配项的bar
获得一行。
While for GroupJoin
, the b
will be a collection of bar
, and you will get a single row for every foo
that has a match. 而对于
GroupJoin
, b
将是bar
的集合,并且每个具有匹配项的foo
都会得到一行。
Both perform an inner join, but if you're looking for SQL's INNER JOIN
, the Join
method is what you want. 两者都执行内部
INNER JOIN
,但是如果您要查找SQL的INNER JOIN
,则需要使用Join
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.