Advertisement
bero_0401

Join / Group

Oct 4th, 2024 (edited)
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | Source Code | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Numerics;
  5. using System;
  6. using revision;
  7.  
  8.  
  9. public class Program
  10. {
  11.  
  12.  
  13.     static void Main(String[] args)
  14.     {
  15.  
  16.         var departments = new List<Department>
  17.         {  new(1 , "HR"),
  18.            new(2 , "Development"),
  19.            new(3 , "IT"),
  20.            new(4 , "Finance"),
  21.            new(6 , "Testing"),
  22.  
  23.         };
  24.         var employees = new List<Employee> {
  25.             new("Abeer", 21 , 4000, 2),
  26.             new("Amr", 29 , 6000, 4),
  27.             new("Ahmed", 25 , 8000, 1),
  28.             new("Omar", 25 , 10000, 3),
  29.             new("Sara", 25 , 10000, 5),
  30.  
  31.         };
  32.  
  33.  
  34.         // Inner Join
  35.  
  36.         //var query = from employee in employees
  37.         //            join department in departments
  38.         //            on employee.DepartmentId equals department.Id
  39.         //            select new { EmployeeName = employee.Name, DepartmentName = department.Name };
  40.  
  41.  
  42.         // Method Syntax
  43.         var query = employees.Join(departments, e => e.DepartmentId, d => d.Id, (e, d) => (e.Name, d.Name));
  44.      
  45.         //foreach (var record in query)
  46.         //{
  47.         //    Console.WriteLine($"{record.EmployeeName} @ {record.DepartmentName}");
  48.         //}
  49.  
  50.  
  51.  
  52.  
  53.         // (Left join + Grouping)
  54.         var query2 = from employee in employees
  55.                     join department in departments
  56.                     on employee.DepartmentId equals department.Id into departmentGroup
  57.                     select new {
  58.                         EmployeeName = employee.Name,
  59.                         DepartmentName = departmentGroup.Select(d => d.Name).FirstOrDefault()
  60.                     };
  61.  
  62.         //foreach (var record in query2)
  63.         //{
  64.         //    Console.WriteLine($"{record.EmployeeName} @ {record.DepartmentName}");
  65.         //}
  66.  
  67.  
  68.  
  69.         // Group
  70.         var records = from employee in employees group employee by employee.DepartmentId;
  71.         foreach (var record in records)
  72.         {
  73.             string emps = string.Join(" , ",record.Select(x => x.Name));
  74.             Console.WriteLine($"Group #{record.Key} : {emps}");
  75.            
  76.         }
  77.  
  78.     }
  79.  
  80.  
  81. }
  82.  
  83.  
  84.  
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement