拡張メソッドを使用して LINQ で左外部結合を実現する
LINQ は、共有キーに基づいて 2 つのテーブルのデータを結合するための重要な操作である左外部結合を実行するための複数の方法を提供します。 join
キーワードは一般的に使用されますが、GroupJoin
や SelectMany
などの拡張メソッドは代替アプローチを提供します。
この例は、拡張メソッドを使用して従来の左外部結合をより流暢な構文に変換する方法を示しています。
<code class="language-csharp">// Left outer join using extension methods var qry = Foo.GroupJoin( Bar, // The second table to join with foo => foo.Foo_Id, // Key selector for the 'Foo' table bar => bar.Foo_Id, // Key selector for the 'Bar' table (x, y) => new // Anonymous type to hold results { Foo = x, // Represents the 'Foo' table entry Bars = y // Represents the matching entries from 'Bar' (or empty if no match) }) .SelectMany( x => x.Bars.DefaultIfEmpty(), // Handles cases where there's no match in 'Bar' (x, y) => new // Anonymous type for final result { Foo = x.Foo, // 'Foo' table entry Bar = y // 'Bar' table entry (might be null if no match) });</code>
このコードは、標準の join
ベースの左外部結合と同じ結果を実現します。 GroupJoin
は、Foo
の要素と、Bar
の対応する一致をグループ化します。 次に、SelectMany
は、DefaultIfEmpty()
を使用してこれらのグループをフラット化し、Foo
に一致しない Bar
エントリも確実に含まれるようにし、結果として得られる匿名型の Bar
プロパティに null 値を設定します。 これにより、完全な左外部結合結果セットが効果的に生成されます。
以上が拡張メソッドを使用してLINQで左外の結合を実行するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。