LINQ Join으로 데이터를 연결하는 방법: C#
약 1분 읽기

조인 작업 Join Operations
조인 은 데이터베이스에 등장하는 개념입니다. 조인 작업은 집합 간에 데이터를 연결합니다. 조인 작업은 클래스 간에 참조 관계가 없더라도 데이터를 연결할 수 있습니다. 이해하기 힘든 개념이므로 공식문서를 읽으면서 익혀주시길 바랍니다. 여기서는 조인 작업이 일반 코드보다 간결하다는 점만 보여드리도록 하겠습니다.
예를 들어, 아래와 같이 정의되어 있을 때 Customer 클래스에 City 속성이 있지만 City 클래스에 Customer 와 관련된 속성이 없으므로 모든 도시에 거주하는 모든 고객의 목록을 구하려면 아래와 같이 복잡한 메서드를 작성해야 합니다.
class Customer
{
public City City { get; set; }
}
class City
{
public string Name { get; set; }
}
public static Enumberable>> FindAllCustomersInCity (Enumberable allCustomers, Enumberable allCities)
{
var customersInCities = new Enumberable>>();
foreach(var city in allCities)
{
// ...
}
}
반면 조인 작업으로 각 도시에 거주하는 모든 고객 집합을 간결하게 구할 수 있습니다.
public static Enumberable>> FindAllCustomersInCity (Enumberable allCustomers, Enumberable allCities) {
var query = from city in allCities
join customer in allCustomers on city.Name equals customer.City.Name into customersInCities
select ( City : city, Customers : customersInCities);
// ...
}