[C# 문법] LINQ의 기본 3장 : LINQ from 중첩하여 사용하기


안녕하세요.

 

오늘은 Linq 구문 3장으로써, Linq에서 원본 데이터를 from을 이용하여 중첩하여 사용하는 방법에 대해서 알려 드리도록 하겠습니다.

 

School 클래스를 선언하고, 반별로 성적이 50점 이상인 학생을 조회하는 구문은 Linq로 작성해 보도록 하겠습니다.


 

예제 코드


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

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Linq_Test

{

    class Program

    {

        static void Main(string[] args)

        {

               School[] _studentArr =

            {

                new School() {_Class = "A", Scores = new int[] { 514575956275 } },

                new School() {_Class = "B", Scores = new int[] { 216572156275 }},

                new School() {_Class = "C", Scores = new int[] { 418573254285 }},

                new School() {_Class = "D", Scores = new int[] { 717574355275 }},

                new School() {_Class = "E", Scores = new int[] { 812575452265 }},

                new School() {_Class = "F", Scores = new int[] { 213577551225 }},

                new School() {_Class = "G", Scores = new int[] { 114595651295 }},

            };

 

            //Linq 구문을 통해서  반별로성적이 50 이상인 학생 조회

            var query = from stu in _studentArr

                        from sc in stu.Scores

                        where sc >= 50

                        orderby sc

                        select new

                        {

                            stu._Class,

                            Lowest = sc

                        };

 

            Console.WriteLine("-------------반별 성적 50 이상인 학생들-------------");

            //출력하기

            foreach(var stu in query)

            {

                string msg = string.Format("학생 이름 :{0} 성적 : {1}", stu._Class, stu.Lowest);

                Console.WriteLine(msg);

            }

        }      

    }

 

    /// <summary>

    /// School 클래스 선언

    /// </summary>

    public class School

    {

        public string _Class { get; set; }

        public int[] Scores { get; set; }

    }

}

 

Colored by Color Scripter

cs

 

실행 결과



위와 같이 이중 from을 이용하여 반별로 50점 이상인 학생을 조회해 보았습니다.

 

감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY