기술공부/언어

[C#] List slicing - Skip과 Take

봉두두 2022. 4. 2. 11:00
728x90

Python에서의 List slicing은 매우 간편하다.

Length 4인 Array에서 index 3부터 끝까지 출력하고싶다면 array[3:]이라고 하면 된다. 매우 간편..

리스트를 거꾸로 출력하고 싶을때는 array[::-1]이라고 하면 된다. 진짜 간편...

 

그럼 C#은 어떨까?

애석하게도 저렇게 간편한 방법으로는 표현할 수가 없다...

그래서 System.Linq 라이브러리에서 제공하는 Skip method와 Take method를 활용하여 Slicing할 수 있다.

 

IEnumerable<T>.Skip<T>(int) | IEnumerable<T>.Take<T>(int)
라이브러리 : System.Linq
Return : An IEnumerable<out T> that contains the elements that occur after the specified index in the input sequence.

 

반드시 using문을 통해 라이브러리를 import한 후 수행하도록 한다.

아래와 같이 사용한다.

string[] test = {"a","p","p","l","e"};

// IEnumerable return값을 string.join으로 묶어 출력할 수 있다.
Console.WriteLine(string.Join("",test.Skip(1).Take(3)));

/* 아래와 같이 수행하면 Return값은 
   System.Linq.Enumerable+ListPartition`1[System.String] 이며
   Enumerable format이 return되는 것을 확인할 수 있다. */
Console.WriteLine(test.Skip(1).Take(3));​
728x90
728x90