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

Esempio di query LINQ

In questa sezione, imparerai alcune query LINQ complesse. Utilizzeremo l'insieme di studenti e standard per le query.

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" }
;

Più Select e operatori where

    Esempio: più Select e operatori where

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

La seguente query restituisce un Enumerable di oggetti anonimi con l'attributo 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));
Output:
John
Bill

Group By

La seguente query restituisce i gruppi di studenti elencati per 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));
}
Output:
StandardID 0:
Ron
StandardID 1:
John
Steve
StandardID 2:
Bill
Ram

L'output include Ron senza StandardID, quindi Ron appartiene a StandardID 0.

Per eliminare gli studenti senza StandardID, usa l'operatore where prima dell'operatore di gruppo:

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 };
Output:
StandardID 1:
John
Steve
StandardID 2:
Bill
Ram

Left outer join

Mostra ogni studente sotto ogni standard utilizzando l'unione esterna destra (Left outer join). Anche se non ci sono studenti assegnati a uno standard, mostra il nome dello standard.

var studentsGroup = from stad in standardList
                    join s in studentList
                    on stad.StandardID equals 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));
}
Output:
Standard 1:
John
Steve
Standard 2:
Bill
Ram
Standard 3:

Nell'esempio di query group by sottostante, ordiniamo i gruppi e selezioniamo solo il Nome dello Studente:

var studentsWithStandard = from stad in standardList
                           join s in studentList
                           on stad.StandardID equals s.StandardID
                           into sg
                               from std_grp in sg 
                               ordinare per stad.StandardName, std_grp.StudentName 
                               select new { 
                                                StudentName = std_grp.StudentName, 
                                                StandardName = stad.StandardName 
                                ;
foreach (var group in studentsWithStandard)
{
    Console.WriteLine("{0} è in {1}", group.StudentName, group.StandardName);
}
Output:
John è in Standard 1
Steve è in Standard 1
Bill è in Standard 2
Ram è in Standard 2

Esempio: Ordinamento

La seguente query restituisce l'elenco degli studenti ordinati per ID Standard e Età in ordine crescente.

var sortedStudents = from s in studentList
                        ordinare per s.StandardID, s.age
                        select new { 
                                StudentName = s.StudentName, 
                                Età = s.age, 
                                IDStandard = s.StandardID};
sortedStudents.ToList().ForEach(s => Console.WriteLine("Nome dello Studente: {0}, Età: {1}, ID Standard: {2}", s.StudentName, s.Age, s.StandardID));
Output:
Nome dello Studente: Ron, Età: 21, ID Standard: 0
Nome dello Studente: John, Età: 18, ID Standard: 1
Nome dello Studente: Steve, Età: 21, ID Standard: 1
Nome dello Studente: Bill, Età: 18, ID Standard: 2
Nome dello Studente: Ram, Età: 20, ID Standard: 2

Join interno (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} è in {1}", s.StudentName, s.StandardName));
Output:
John è in Standard 1
Steve è in Standard 1
Bill è in Standard 2
Ram è in Standard 2

Query annidate

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));
Output:
Steve