English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Nesta seção, você aprenderá algumas consultas LINQ complexas. Usaremos as seguintes coleções de alunos e padrões para as 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"} };
Exemplo: múltiplos operadores Select e Where
var studentNames = studentList.Where(s => s.Age > 18) .Select(s => s) .Where(st => st.StandardID > 0) .Select(s => s.StudentName);
Steve Ram
A consulta retornada a seguir contém objetos anônimos com apenas a propriedade StudentName: Enumerable:
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
A consulta a seguir retorna os grupos de alunos listados pelo 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
A saída inclui Ron sem nenhum StandardID, portanto Ron pertence ao StandardID 0.
Para excluir alunos sem StandardID, use o operador where antes do operador de agrupamento:
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
Use o join externo à esquerda (Left outer join) para mostrar todos os alunos de cada padrão. Mesmo que não haja alunos atribuídos a esse padrão, a nomeação do padrão deve ser exibida.
var studentsGroup = from stad in standardList join s in studentList onde stad.ID do Standard iguala s.ID do Estudante 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)); }
Standard 1: John Steve Standard 2: Bill Ram Standard 3:
No exemplo de consulta group by a seguir, ordenamos os grupos e escolhemos apenas Nome do Estudante:
var studentsWithStandard = from stad in standardList join s in studentList onde stad.ID do Standard iguala s.ID do Estudante into sg from std_grp in sg ordernar por stad.Nome do Standard, std_grp.Nome do Estudante select new { Nome do Estudante = std_grp.StudentName, StandardName = stad.StandardName }; foreach (var group in studentsWithStandard) { 1} }
John está em Standard 1 Steve está em Standard 1 Bill está em Standard 2 Ram está em Standard 2
A seguinte consulta retorna a lista de alunos ordenada por ID do Estudante e Idade em ordem crescente.
var sortedStudents = from s in studentList ordernar por s.StandardID, s.age select new { StudentName = s.StudentName, Idade = s.age, ID do Estudante = s.StandardID;} sortedStudents.ToList().ForEach(s => Console.WriteLine("Nome do Estudante: {0}, Idade: ",1}, ID do Estudante: {2});
Nome do Estudante: Ron, Idade: 21, ID do Estudante: 0 Nome do Estudante: John, Idade: 18, ID do Estudante: 1 Nome do Estudante: Steve, Idade: 21, ID do Estudante: 1 Nome do Estudante: Bill, Idade: 18, ID do Estudante: 2 Nome do Estudante: Ram, Idade: 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á em {1}
John está em Standard 1 Steve está em Standard 1 Bill está em Standard 2 Ram está em 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