简体   繁体   中英

LINQ, INNER JOIN (Join or GroupJoin)?

I am kind of lost between Join and GroupJoin. Which way is the right way to do INNER JOIN? On one hand Join is doing the right job, but I have to call Distinct. On the other hand GroupJoin is grouping by itself, but gives me empty 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.

For Join , the b will be a single bar , and you will get a row for every bar that has a match.

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.

Both perform an inner join, but if you're looking for SQL's INNER JOIN , the Join method is what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM