16
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LINQの結合で複数キーを使用する方法

Last updated at Posted at 2018-04-05

#はじめに
LINQで結合を行う際、複数キーを使用したいときについてのメモです。
間違いや勘違いに関しましてはご指摘いただけると幸いです。

テーブルのイメージ

PersonTable
string PersonID
strijng Name
int Age
string TeamID
int SmallTeamID
TeamTable
string TeamID
int SmallTeamID
string TeamName

複数のキーでの結合はSQLでは以下のように書きます。

SELECT p.PersonID AS PersonID, p.Name AS Name, t.TeamName AS TeamName
FROM PersonTable AS p
INNER JOIN TeamTable AS t
    ON p.TeamID = t.TeamID
    AND p.SmallTeamID = t.SmallTeamID;

LINQではJOINでのANDにあたるものがないため、結合キーを匿名型で生成します。

###クエリ式

var query = from p in PersonTable
            join t in TeamTable
            on new {p.TeamID, p.SmallTeamID}
            equals new {p.TeamID, p.SmallTeamID}
            where p.Age > 25
            select new
            {
                PersonID = p.PersonID,
                Name = p.Name,
                TeamName = t.TeamName
            };

###メソッド構文

var query = PersonTable
            .Join(
                TeamTable,
                t => new { t.TeamID, t.SmallTeamID },
                p => new { p.TeamID, p.SmallTeamID },
                where p.Age > 25
                (person, team) => new
                {
                    UserID = person.UserID,
                    Name = person.UserName,
                    TeamName = team.DepartmentName
                }
            );

この結合キーは

 {string TeamID, int SmallTeamID}

という構造になります。
この匿名型が一致する行で結合が行われます。

16
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?