Mega Code Archive

 
Categories / C# Tutorial / LINQ
 

Construct instance for nested class

using System; using System.Collections.Generic; using System.Linq; using System.Text;     class Employee     {         public string Name { get; set; }         public decimal Salary { get; set; }     }     class Department     {         public string Name { get; set; }         List<Employee> employees = new List<Employee>();         public IList<Employee> Employees         {             get { return employees; }         }     }     class Company     {         public string Name { get; set; }         List<Department> departments = new List<Department>();         public IList<Department> Departments         {             get { return departments; }         }     }     class SalaryReport     {         static void Main()         {             var company = new Company             {                 Name = "A",                 Departments =                 {                     new Department                      {                          Name = "Development",                          Employees =                          {                             new Employee { Name = "T", Salary = 75000m },                             new Employee { Name = "D", Salary = 45000m },                             new Employee { Name = "M", Salary = 150000m }                         }                     },                     new Department                      {                          Name = "Marketing",                          Employees =                          {                             new Employee { Name = "Z", Salary = 200000m },                             new Employee { Name = "X", Salary = 120000m }                         }                     }                 }             };             var query = company.Departments                                .Select(dept => new { dept.Name, Cost = dept.Employees.Sum(person => person.Salary) })                                .OrderByDescending(deptWithCost => deptWithCost.Cost);             foreach (var item in query)             {                 Console.WriteLine(item);             }         }     }