English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Exemple de requête LINQ

Dans cette section, vous apprendrez quelques requêtes LINQ complexes. Nous utiliserons les ensembles de étudiants et de normes suivants pour les requêtes.

IList<Student> studentList = new List<Student>() { 
    new Student() { StudentID = 1, StudentName = "John",     Age = 18, StandardID = 1 }, ,
    new Student() { StudentID = 2, StudentName = "Steve",     Age = 21, StandardID = 1 }, ,
    new Student() { StudentID = 3, StudentName = "Bill",     Age = 18, StandardID = 2 }, ,
    new Student() { StudentID = 4, StudentName = "Ram" , Age = 20, StandardID = 2 }, ,
    new Student() { StudentID = 5, StudentName = "Ron" , Age = 21 } 
};
IList<Standard> standardList = new List<Standard>() { 
    new Standard() { StandardID = 1, StandardName="Standard 1},
    new Standard() { StandardID = 2, StandardName="Standard 2},
    new Standard() { StandardID = 3, StandardName="Standard 3"}
};

Exemple : multiples opérateurs Select et Where

    Exemple : multiples opérateurs Select et Where

var studentNames = studentList.Where(s => s.Age > 18)
                              .Select(s => s)
                              .Where(st => st.StandardID > 0)
                              .Select(s => s.StudentName);
Sortie :
Steve
Ram

L'interrogation suivante renvoie un Enumerable d'objets anonymes uniquement avec l'attribut StudentName :

var teenStudentsName = from s in studentList
                       where s.age > 12 && s.age < 20
                       select new { StudentName = s.StudentName };
teenStudentsName.ToList().ForEach(s => Console.WriteLine(s.StudentName));
Sortie :
John
Bill

Group By

La requête suivante renvoie les groupes d'étudiants listés par StandardID :

var studentsGroupByStandard = from s in studentList
                              group s by s.StandardID into sg
                              orderby sg.Key 
                                    select new { sg.Key, sg };
foreach (var group in studentsGroupByStandard)

    Console.WriteLine("StandardID {0}:", group.Key);
    
    group.sg.ToList().ForEach(st => Console.WriteLine(st.StudentName));
}
Sortie :
StandardID 0:
Ron
StandardID 1:
John
Steve
StandardID 2:
Bill
Ram

La sortie inclut Ron sans StandardID, donc Ron appartient à StandardID 0.

Pour supprimer les étudiants sans StandardID, utilisez l'opérateur where avant l'opérateur de groupe :

var studentsGroupByStandard = from s in studentList
                              where s.StandardID > 0
                              group s by s.StandardID into sg
                              orderby sg.Key 
                                    select new { sg.Key, sg };
Sortie :
StandardID 1:
John
Steve
StandardID 2:
Bill
Ram

Left outer join

Utilisez le left outer join pour afficher les étudiants sous chaque norme. Même si aucun étudiant n'est assigné à cette norme, affichez le nom de la norme.

var studentsGroup = from stad in standardList
                    join s in studentList
                    on stad.StandardID égale à s.StandardID
                        into sg
                        select new { 
                                        StandardName = stad.StandardName, 
                                        Students = sg 
                                    };
foreach (var group in studentsGroup)

    Console.WriteLine(group.StandardName);
    
    group.Students.ToList().ForEach(st => Console.WriteLine(st.StudentName));
}
Sortie :
Niveau 1:
John
Steve
Niveau 2:
Bill
Ram
Niveau 3:

Dans l'exemple de requête group by suivant, nous trions les groupes et sélectionnons uniquement Nom d'étudiant:

var studentsWithStandard = from stad in standardList
                           join s in studentList
                           on stad.StandardID égale à s.StandardID
                           into sg
                               from std_grp in sg 
                                
                               select new { 
                                                 
                                                StandardName = stad.StandardName 
                                };


    1}
}
Sortie :
John est dans Standard 1
Steve est dans Standard 1
Bill est dans Standard 2
Ram est dans Standard 2

Exemple de tri

La requête suivante retourne la liste des étudiants triés par Identifiant de niveau et Âge en ordre croissant.

var sortedStudents = from s in studentList
                        Tri par Identifiant de niveau, Âge
                        select new { 
                                StudentName = s.StudentName, 
                                Âge = s.age, 
                                Identifiant de niveau = s.StandardID;}
sortedStudents.ToList().ForEach(s => Console.WriteLine("Nom d'étudiant: {0}, Âge: ",1}, Identifiant de niveau: {2});
Sortie :
Nom d'étudiant: Ron, Âge: 21, Identifiant de niveau: 0
Nom d'étudiant: John, Âge: 18, Identifiant de niveau: 1
Nom d'étudiant: Steve, Âge: 21, Identifiant de niveau: 1
Nom d'étudiant: Bill, Âge: 18, Identifiant de niveau: 2
Nom d'étudiant: Ram, Âge: 20, StandardID: 2

Jointure interne (Inner Join)

var studentWithStandard = from s in studentList
                          join stad in standardList
                          on s.StandardID equals stad.StandardID 
                          select new { 
                                  StudentName = s.StudentName, 
                                  StandardName = stad.StandardName 
                              };
studentWithStandard.ToList().ForEach(s => Console.WriteLine("{0} est dans {1}
Sortie :
John est dans Standard 1
Steve est dans Standard 1
Bill est dans Standard 2
Ram est dans Standard 2

Requêtes imbriquées

var nestedQueries = from s in studentList
                    where s.age > 18 && s.StandardID == 
                        (from std in standardList
                        where std.StandardName == "Standard" 1"
                        select std.StandardID).FirstOrDefault()
                            select s;
nestedQueries.ToList().ForEach(s => Console.WriteLine(s.StudentName));
Sortie :
Steve