Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
05-17 00:00
관리 메뉴

nomad-programmer

[Programming/C#] System.Array 본문

Programming/C#

[Programming/C#] System.Array

scii 2020. 9. 14. 15:11

C#에서는 모든 것이 객체이다. 배열도 객체이며 당연히 기반이 되는 형식이 있다. .NET Framework의 CTS (Common Type System) 에서 배열은 System.Array 클래스에 대응된다.
따라서 System.Array의 특성과 메소드를 파악하면 배열의 특성과 메소드를 알게 되는 셈이다.

Array 클래스의 주요 메소드와 프로퍼티

분류 이름 설명
정적 메소드 Sort() 배열을 정렬한다.
BinarySearch<T>() 이진 탐색을 수행한다.
IndexOf() 배열에서 찾고자 하는 특정 데이터의 인덱스를 반환한다.
TrueForAll<T>() 배열의 모드 요소가 지정한 조건에 부합하는지의 여부를 반환한다.
FindIndex<T>() 배열에서 지정한 조건에 부합하는 첫 번째 요소의 인덱스를 반환한다.
IndexOf() 메소드가 특정 값을 찾는데 비해, FindIndex<T>() 메소드는 지정한 조건에 바탕하여 값을 찾는다.
Resize<T>() 배열의 크기를 재조정한다.
Clear() 배열의 모든 요소를 초기화한다. 배열이 숫자 형식 기반이면 0으로, 논리 형식 기반이면 false로, 참조 형식 기반이면 null로 초기화한다.
ForEach<T>() 배열의 모든 요소에 대해 동일한 작업을 수행하게 한다.
인스턴스 메소드 GetLength() 배열에서 지정한 차원의 길이를 반환한다. (다차원 배열에서 유용)
프로퍼티 Length 배열의 길이를 반환한다.
Rank 배열의 차원을 반환한다.

<T> 는 형식 매개 변수 (Type Parameter) 라고 한다. 메소드를 호출할 때는 T 대신 배열의 기반 자료형을 매개 변수로 입력하면 컴파일러가 해당 형식에 맞춰 동작하도록 메소드를 컴파일한다.

Array 클래스의 메소드와 프로퍼티를 활용하는 예제

using System;

namespace test
{
    internal class Program
    {
        private static bool CheckPassed(int score)
        {
            return score >= 60;
        }

        private static void Print(int value)
        {
            Console.Write($"{value} ");
        }

        public static void Main(string[] args)
        {
            int[] scores = new int[] {80, 74, 81, 90, 34};

            foreach (int score in scores)
            {
                Console.Write($"{score} ");
            }

            Console.WriteLine();

            Array.Sort(scores);
            Array.ForEach<int>(scores, new Action<int>(Print));
            Console.WriteLine();

            Console.WriteLine($"Number of dimensions : {scores.Rank}");

            Console.WriteLine("Binary Search: 80 is at {0}",
                Array.BinarySearch<int>(scores, 81));
            Console.WriteLine("Linear Search: 90 is at {0}",
                Array.IndexOf(scores, 90));

            // TrueForAll 메소드는 배열과 함께 조건을 검사하는 메소드를 매개 변수로 받는다.
            Console.WriteLine("Everyone passed ? : {0}",
                Array.TrueForAll<int>(scores, CheckPassed));

            // FindIndex 메소드는 특정 조건에 부합하는 메소드를 매개 변수로 받는다.
            // 여기에선 익명 메소드로 구현되었다.
            int index = Array.FindIndex<int>(scores,
                delegate(int score)
                {
                    return score < 60;
                });

            scores[index] = 61;

            Console.WriteLine("Everyone passed ? : {0}",
                Array.TrueForAll<int>(scores, CheckPassed));
            
            Console.WriteLine($"old length of scores : {scores.GetLength(0)}");

            // 크기가 5인 배열을 10으로 재조정.
            Array.Resize<int>(ref scores, 10);

            Console.WriteLine($"new length of scores : {scores.Length}");

            // Action 대리자
            Array.ForEach<int>(scores, new Action<int>(Print));
            Console.WriteLine();
            
            Array.Clear(scores, 3, 7);

            Array.ForEach<int>(scores, new Action<int>(Print));
            Console.WriteLine();
        }
    }
}


/* 결과

80 74 81 90 34 
34 74 80 81 90 
Number of dimensions : 1
Binary Search: 80 is at 3
Linear Search: 90 is at 4
Everyone passed ? : False
Everyone passed ? : True
old length of scores : 5
new length of scores : 10
61 74 80 81 90 0 0 0 0 0 
61 74 80 0 0 0 0 0 0 0 

*/
Comments