LINQ,INNER JOIN(加入还是GroupJoin)?

时间:2019-06-17 02:05:35

标签: c# linq

在Join和GroupJoin之间我有点迷茫。进行INNER JOIN的正确方法是哪一种?一方面,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);
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

了解这一点的关键是查看您传入的最后一个lambda的参数类型。

对于Joinb将是单个bar,并且您将为每个具有匹配项的bar获得一行。

对于GroupJoinb将是bar的集合,并且您将为每个具有匹配项的foo获得一行。

两者都执行内部联接,但是如果您要查找SQL的INNER JOIN,则需要使用Join方法。