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

LINQ 쿼리 예제

이 장에서는 복잡한 LINQ 쿼리를 배웁니다. 다음 학생과 표준 셋을 사용하여 쿼리를 수행합니다.

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

多个Select和where运算符

    예제:多个Select和where运算符

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

이 쿼리는 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

Group By

다음 쿼리는 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

StandardID가 없는 Ron을 포함하는 출력이 있으므로, Ron은 StandardID 0에 속합니다.

StandardID가 없는 학생을 제거하려면, 그룹 연산자 앞에 where 연산자를 사용하십시오:

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

Left outer join

왼쪽 외부 조인(Left outer join)을 사용하여 각 표준 아래의 학생을 표시합니다. 해당 표준에 할당되지 않은 학생도 표시합니다.

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));
}
출력:
스탠다드 1:
John
Steve
스탠다드 2:
Bill
Ram
스탠다드 3:

다음 group by 쿼리 예제에서, 우리는 그룹을 정렬하고 StudentName만 선택합니다:

var studentsWithStandard = from stad in standardList
                           join s in studentList
                           on stad.StandardID equals s.StandardID
                           into sg
                               from std_grp in sg 
                               orderby stad.StandardName, std_grp.StudentName 
                               select new { 
                                                StudentName = std_grp.StudentName, 
                                                StandardName = stad.StandardName 
                                };
foreach (var group in studentsWithStandard)
{
    Console.WriteLine("{0}는 {1}
}
출력:
John이 Standard에 있음 1
Steve이 Standard에 있음 1
Bill이 Standard에 있음 2
Ram이 Standard에 있음 2

정렬

다음 쿼리는 StandardID와 Age를 기준으로 오름차순으로 학생 목록을 반환합니다.

var sortedStudents = from s in studentList
                        orderby s.StandardID, s.age
                        select new { 
                                StudentName = s.StudentName, 
                                Age = s.age, 
                                StandardID = s.StandardID };
sortedStudents.ToList().ForEach(s => Console.WriteLine("학생 이름: {0}, 나이: ",1, 스탠다드 아이디: {2}
출력:
학생 이름: Ron, 나이: 21, 스탠다드 아이디: 0
학생 이름: John, 나이: 18, 스탠다드 아이디: 1
학생 이름: Steve, 나이: 21, 스탠다드 아이디: 1
학생 이름: Bill, 나이: 18, 스탠다드 아이디: 2
학생 이름: Ram, 나이: 20, StandardID: 2

내부 조인(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}는 {1}
출력:
John이 Standard에 있음 1
Steve이 Standard에 있음 1
Bill이 Standard에 있음 2
Ram이 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