簡體   English   中英

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

[英]LINQ, INNER JOIN (Join or GroupJoin)?

我在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);
    }
}

謝謝!

理解這一點的關鍵是查看您傳入的最后一個lambda的參數類型。

對於Joinb將是單個bar ,並且您將為每個具有匹配項的bar獲得一行。

而對於GroupJoinb將是bar的集合,並且每個具有匹配項的foo都會得到一行。

兩者都執行內部INNER JOIN ,但是如果您要查找SQL的INNER JOIN ,則需要使用Join方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM