[C#] LINQ 쿼리 구문

C# 에서는 SQL 구문에서나 사용된 select, where, from 등의 구문을 사용하거나 구문과 동일한 역할을 하는 메소드들로 동일한 결과를 얻을 수 있다.

구문을 사용하는 경우, 일반적인 SQL 구문과는 형식이 거의 역순으로 사용된다.

예시)


- from 사용할 배열이나 데이터 타입의 나열 in 저장 변수 where 조건식 select 출력 변수


또한 LINQ 쿼리 구문으로 출력된 값은 별도의 데이터 타입의 변수에 저장 하여야 한다.

IEnumerable <타입> 변수명


예제) 학생 정보를 저장한 클래스 리스트에 대한 LINQ 쿼리

- 첫 번째 과목의 점수가 90점 이상한 학생 정보의 출력

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class A {
    public class Student
    {
        public string First { get; set; }
        public string Last { get; set; }
        public int ID { get; set; }
        public List<int> Scores;
    }
 
    // Create a data source by using a collection initializer.
    static List<Student> students = new List<Student>
{
    new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97928160}},
    new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75849139}},
    new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88946591}},
    new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97898582}},
    new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35729170}},
    new Student {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99869094}},
    new Student {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93928087}},
    new Student {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92908378}},
    new Student {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68798892}},
    new Student {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99828179}},
    new Student {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96859160}},
    new Student {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94929191}}
};
 
    static void Main(String[] args) {
        IEnumerable<Student> firstScore = from student in students where student.Scores[0> 90 select student; //첫번째 점수가 90점 이상의 학생들에 대한 정보를  
 
        foreach (Student student in firstScore){
            Console.WriteLine(student.First+" "+student.Last);
        }
    }
 
}
cs

-실행 결과



댓글