我有点迷失在Join和GroupJoin之间。哪种方式是进行内连接的正确方式?一方面,Join正在做正确的工作,但我必须调用Distinct。另一方面,GroupJoin本身是分组的,但给我的RHS是空的。还是有更好的方法?
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);
}
}谢谢!
发布于 2019-06-17 10:14:17
理解这一点的关键是查看您传入的最后一个lambda的参数类型。
对于Join,b将是单个bar,并且您将为每个具有匹配的bar获得一行。
而对于GroupJoin,b将是bar的集合,对于每个匹配的foo,您将获得一行。
这两个方法都执行内部连接,但是如果您正在寻找SQL的INNER JOIN,那么Join方法就是您想要的。
https://stackoverflow.com/questions/56623957
复制相似问题