[C# 문법] C# Linq Take, Skip 이용하여 필요한 구역 잘라내기


안녕하세요.

 

오늘은 C# 문법에서 Linq에 대해서 알려 드리려고 합니다. 그 중에서도 배열에서 사용자가 필요한 구역만 잘라내는 방법에 대해서 알려 드리려고 하는데요.

 

Linq에서는 TakeSkip을 이용하여 손 쉽게 필요한 구역만 잘라내서 표현할 수 있습니다.

 

바로 아래 예제를 통해서 TakeSkip 사용법 및 둘의 차이점을 보여 드릴게요.


 

예제 코드


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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace LinqTest

{

    class Program

    {

        static void Main(string[] args)

        {

            string[] fruits = { "Apple""Orange""Peach",

                "Wartermelon""Melon""Banana""Grape" };

 

            var takeResult = fruits.Take(3);

 

            //Take 구역 잘라내기

            foreach(string str in takeResult)

            {

                Console.WriteLine($"Take(3)  값은 {str} 입니다.");

            }

 

            Console.WriteLine();

            Console.WriteLine();

 

            var skipResult = fruits.Skip(3);

 

            //Skip 구역 잘라내기

            foreach(string str in skipResult)

            {

                Console.WriteLine($"Skip(3)  값은 {str} 입니다.");

            }

        }

    }

}

 

Colored by Color Scripter

cs

 

실행 결과



위와 같이 Take는 숫자 만큼 앞에서 출력을 해주고, Skip은 그 숫자 를 건너뛴 나머지 뒤의 값들을 출력해 주는 것을 확인하실 수 있습니다.

또 아래와 같이 TakeSkip을 혼용해서 같이 사용할 수도 있습니다.

 

예제 코드


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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace LinqTest

{

    class Program

    {

        static void Main(string[] args)

        {

            string[] fruits = { "Apple""Orange""Peach",

                "Wartermelon""Melon""Banana""Grape" };

 

            var result = fruits.Skip(2).Take(3);

 

            //Skip, Take 같이 사용

            foreach(string str in result)

            {

                Console.WriteLine($"값은 {str} 입니다.");

            }

        }

    }

}

 

Colored by Color Scripter

cs

 

실행 결과



위와 같이 Skip(2).Take(3) 이라고 Linq 표현식을 작성했는데요.

 

이 뜻은 앞에 2개는 건너 뛰고, 뒤에 3개의 값만 구문해서 보여줘라 라는 의미로 해석하시면 되겠습니다.

 

이처럼 Skip Take 함께 사용도 가능합니다.

 

글 읽어 주셔서 감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY