CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var department1 = new Department { Id = 1, Name = "Foo" };
var department2 = new Department { Id = 2, Name = "Bar" };
var employeeRepository = new List<Employee>
{
new Employee
{
Id = 1,
Name = "John",
Address = "Lorem Ipsum",
Department = department1,
DepartmentId = department1.Id
},
new Employee
{
Id = 2,
Name = "Bill",
Address = "Lorem Ipsum 22",
Department = department2,
DepartmentId = department2.Id
}
};
var result = employeeRepository.Select(e => new EmployeeWithDepartmentDto { EmployeeName = e.Name, EmployeeAddress = e.Address, DepartmentName = e.Department.Name });
foreach (var employeeWithDepartmentDto in result)
{
Console.WriteLine($"Name: {employeeWithDepartmentDto.EmployeeName}, Address: {employeeWithDepartmentDto.EmployeeAddress}, Department: {employeeWithDepartmentDto.DepartmentName}");
}
}
public class EmployeeWithDepartmentDto
{
public string EmployeeName { get; set; }
public string EmployeeAddress { get; set; }
public string DepartmentName { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public int DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
}