C#

LINQ Left Outer Join 사용법

지오준 2021. 7. 23. 13:20
반응형

Left Outer Join(왼쪽 외부조인)는 기준이 되는 데이터를 모두 반환합니다.

샘플코드는 UserGroup테이블이 기준이 되는 데이터이므로 모든 그룹명이 조회되지만

Seventeen의 경우에는 User테이블에 해당 그룹의 멤버명이 존재하지 않으므로 멤버명은 반환이 되지않습니다.

/// <summary>
/// Group정보 클래스
/// </summary>
class UserGroup
{
	public string GroupName { get; set; }	
	public string UserGroupID { get; set; }
}

/// <summary>
/// User정보 클래스
/// </summary>
class User
{
	public string UserName { get; set; }
	public string UserGroupID { get; set; }
}

static void Main(string[] args)
{
	//Group클래스 샘플데이터
	List<UserGroup> UserGroups = new List<UserGroup>()
	{
		new UserGroup{GroupName="Bts",  UserGroupID="1"},
		new UserGroup{GroupName="Shinee",  UserGroupID="2"},
		new UserGroup{GroupName="Tvxq", UserGroupID="3"},
		new UserGroup{GroupName="Twice", UserGroupID="4"},
		new UserGroup{GroupName="Seventeen", UserGroupID="5"},
	};

	// User클래스 샘플데이터
	List<User> Users = new List<User>()
	{
		new User(){UserName="V", UserGroupID="1"},
		new User(){UserName="SUGA", UserGroupID="1"},
		new User(){UserName="JIN", UserGroupID="1"},
		new User(){UserName="KEY", UserGroupID="2"},
		new User(){UserName="MINHO", UserGroupID="2"},
		new User(){UserName="CHANGMIN", UserGroupID="3"},
		new User(){UserName="MINA", UserGroupID="4"},
		new User(){UserName="SANA", UserGroupID="4"},
		new User(){UserName="MOMO", UserGroupID="4"},
	};

	//Left Outer Join 쿼리
	var innerJoinQuery =
		from userGroup in UserGroups
		join user in Users on userGroup.UserGroupID equals user.UserGroupID into leftJoin
		from user in leftJoin.DefaultIfEmpty()
		select new { UserGroupID = userGroup.UserGroupID, GroupName = userGroup.GroupName, UserName = (user != null ? user.UserName : string.Empty) };

	Console.WriteLine("Left Outer Join Query");
	//UserGroup테이블에 존재하는 모든 데이터 반환
	foreach (var item in innerJoinQuery)
	{
		Console.WriteLine("({0}-{2}){1}", item.GroupName, item.UserName, item.UserGroupID);
	}
	Console.ReadKey();
}

결과값

LinqSample9.zip
0.21MB

반응형