English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
En esta sección, aprenderás algunas consultas LINQ complejas. Utilizaremos las siguientes colecciones de estudiantes y estándares para las consultas.
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"} };
Ejemplo: múltiples operadores Select y Where
var studentNames = studentList.Where(s => s.Age > 18) .Select(s => s) .Where(st => st.StandardID > 0) .Select(s => s.StudentName);
Steve Ram
La consulta siguiente devuelve un Enumerable de objetos anónimos que solo tienen la propiedad 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));
John Bill
La siguiente consulta devuelve los grupos de estudiantes listados por 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)); }
StandardID 0: Ron StandardID 1: John Steve StandardID 2: Bill Ram
La salida incluye a Ron sin ningún StandardID, por lo que Ron pertenece al StandardID 0.
Para eliminar estudiantes sin StandardID, utilice el operador where antes del operador de agrupamiento:
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 };
StandardID 1: John Steve StandardID 2: Bill Ram
Mostrar cada estudiante bajo cada estándar utilizando una unión externa izquierda (Left outer join). Incluso si no se ha asignado ningún estudiante a ese estándar, también se mostrará el nombre del estándar.
var studentsGroup = from stad in standardList unir s en studentList on stad.ID de Estándar iguala s.ID de Estándar 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.NombreEstudiante)); }
Estándar 1: John Steve Estándar 2: Bill Ram Estándar 3:
En el siguiente ejemplo de consulta group by, ordenamos los grupos y seleccionamos solo Nombre de Estudiante:
var studentsWithStandard = from stad in standardList unir s en studentList on stad.ID de Estándar iguala s.ID de Estándar into sg from std_grp in sg ordenar por stad.NombreEstándar, std_grp.NombreEstudiante select new { Nombre de Estudiante = std_grp.NombreEstudiante, StandardName = stad.StandardName }; foreach (var grupo in studentsWithStandard) { 1} }
John está en Standard 1 Steve está en Standard 1 Bill está en Standard 2 Ram está en Standard 2
La siguiente consulta devuelve una lista de estudiantes ordenada por ID de Estándar y Edad en orden ascendente.
var sortedStudents = from s in studentList ordenar por s.StandardID, s.age select new { StudentName = s.StudentName, Edad = s.age, ID de Estándar = s.StandardID }; sortedStudents.ToList().ForEach(s => Console.WriteLine("Nombre de Estudiante: {0}, Edad: ",1}, ID de Estándar: {2});
Nombre de Estudiante: Ron, Edad: 21, ID de Estándar: 0 Nombre de Estudiante: John, Edad: 18, ID de Estándar: 1 Nombre de Estudiante: Steve, Edad: 21, ID de Estándar: 1 Nombre de Estudiante: Bill, Edad: 18, ID de Estándar: 2 Nombre de Estudiante: Ram, Edad: 20, StandardID: 2
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á en {1});
John está en Standard 1 Steve está en Standard 1 Bill está en Standard 2 Ram está en Standard 2
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));
Steve