Advertisement
fcamuso

Linq C

Nov 24th, 2021
1,311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Linq_B_join
  6. {
  7.   public class Studente
  8.   {
  9.     public int StudenteID { get; set; }
  10.     public string StudenteNome { get; set; }
  11.     public int ClasseID { get; set; }
  12.   }
  13.  
  14.   public class Classe
  15.   {
  16.     public int ClasseIDx { get; set; }
  17.     public string ClasseNome { get; set; }
  18.   }
  19.  
  20.   class Program
  21.   {
  22.     static void Main(string[] args)
  23.     {
  24.       List<Studente> StudenteList = new List<Studente>() {
  25.       new Studente() { StudenteID = 1, StudenteNome = "Giovanni", ClasseID =1 },
  26.       new Studente() { StudenteID = 2, StudenteNome = "Massimo", ClasseID =1 },
  27.       new Studente() { StudenteID = 3, StudenteNome = "Sandra", ClasseID =2 },
  28.       new Studente() { StudenteID = 4, StudenteNome = "Romeo" , ClasseID =2 },
  29.       new Studente() { StudenteID = 5, StudenteNome = "Silvia", ClasseID =5 } };
  30.  
  31.       List<Classe> ClasseList = new List<Classe>() {
  32.         new Classe(){ ClasseIDx = 1, ClasseNome="Classe 1"},
  33.         new Classe(){ ClasseIDx = 2, ClasseNome="Classe 2"},
  34.         new Classe(){ ClasseIDx = 3, ClasseNome="Classe 3"}
  35.     };
  36.  
  37.  
  38.     var lista = ClasseList.Join( //lato molti
  39.         StudenteList,  //lato uno
  40.        
  41.         Classe => Classe.ClasseIDx,  // chiave primaria
  42.         Studente => Studente.ClasseID,    // chiave esterna
  43.         (Classe, Studente) => new  // risultato
  44.         {
  45.           StudenteNome = Studente.StudenteNome,
  46.           ClasseNome = Classe.ClasseNome
  47.         });
  48.  
  49.       foreach (var obj in lista) Console.WriteLine($"{obj.StudenteNome} frequenta la classe {obj.ClasseNome}");  
  50.     }
  51.   };
  52.  
  53.    
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement