배열, 딕셔너리, 템플릿

doyeon kim·2025년 1월 20일

C#

목록 보기
5/13

배열 선언

static void Main(string[] args)
        {
            int[] testArr = new int[5] {0,0,0,0,0 }; 
            // 초기화 시 모든 인덱스 초기화해야됨(5개면 5개 다 작성)


            for (int i = 0; i < testArr.Length; i++)
            {
                testArr[i] = 1 + i;
                //Console.WriteLine(testArr[i]); => 1,2,3,4,5
            }

            Array.Reverse(testArr); // => 반대로(5,4,3,2,1)

            string[] testStArr = new string[] { "aa", "bb", "", "" };

            Console.ReadKey();

        }

foreach : 배열의 각 요소에 접근

 string[] testStArr = new string[] { "aa", "bb", "cc", "dd", "ee" };

            foreach (string item in testStArr)
            {
                // item = "abc";    이런식으로 사용불가 (item 값은 testArr 값을 복사해서 사용하기 때문에)
                string tempstr = item;   // 이렇게는 사용 가능
            }

다차원 배열

int[,] indexArr = new int[3, 4]  // 2차원 배열 [행.열] 순서
            {
                {1,2,3,4 },
                {5,6,7,8 },
                {9,10,11,12}
            };
            
            
            
int[,,] thirdArr = new int[2, 3, 4]  // 3차원 배열 [z좌표,행,열] 순서
            {
                {
                    {1,2,3,4 },
                    {5,6,7,8 },
                    {9,10,11,12}
                },

                 {
                    {1,2,3,4 },
                    {5,6,7,8 },
                    {9,10,11,12}
                },

            };

            indexArr[1, 2] = 10;

            int size = indexArr.Length;
            int fSize = indexArr.GetLength(0);
            int dimSize = indexArr.Rank;
  • size : indexArr 의 총 길이 -> 3*4 = 12
  • fSize : indexArr 의 0번째 행의 길이 -> 3
  • dimSize : indexArr 의 차수 -> 2
 int[][] arr2by = new int[3][];
            arr2by[0] = new int[5];  // 첫 번째 행의 크기는 5
            arr2by[1] = new int[2];	 // 두 번째 행의 크기는 2
            arr2by[2] = new int[3]; // 세 번째 행의 크기는 3

            arr2by[0][1] = 3;

int[][] arr2by = new int[3][];
=> 배열의 행의 크기만 지정하고 열의 크기는 각각 설정하고 싶을 때

※ int[,] indexArr = new int[3, 4] 시 각 배열은 메모리 상 이어져 있지만
int[][] arr2by = new int[3][]; 시에는 각각 분리되어 있음


예제(다차원 배열 vs 클래스)

 //  배열을 이용한 성적 출력
 	int[,] kor1 = new int[,] { { 1, 2, 3, 10, 20, 30 }, { 4, 5, 6, 40, 50, 60 } };
	string[] name = new string[] { "aaa", "bbb", "ccc" };
	Console.WriteLine($"{name[0]} 의 국어성적 : {kor1[0, 1]}");
    
// 클래스를 이용한 성적 출력    

class Student
    {
        public int kor;
        public string name;
        public Student(string name, int kor)
        {
            this.name = name;
            this.kor = kor;
        }
    }
    
 Student[] student = new Student[10];
student[0] = new Student("aaa", 2);
student[1] = new Student("bbb", 20);

Console.WriteLine($"{student[0].name} 의 국어성적 : {student[0].kor}");
    

배열이 다차원으로 갈수록 선언이나 이해가 힘들어진다.
-> 최대한 간결한 배열을 사용하면서 클래스를 이용


리스트(List)

 List<int> intList = new List<int>();
            intList.Add(10);  // 추가
            intList.Add(20);
            intList.Add(30);
            intList.Add(40);
            intList.Add(50);
            intList.RemoveAt(4); // 4번 인덱스에 요소 제거
            intList.Remove(10);  // 값이 10인 요소 제거
            intList[5] = 30; // 해당 공간이 할당되지 않음 -> 문법 오류는 안나지만 런타임 에러 발생
            int LSize = intList.Count; // 리스트의 크기 

크기를 선언해야 하는 배열과 다르게 요소들을 중간에 추가 및 제거할 수 있다


딕셔너리(Dictionary)

    Dictionary<string, string> dict = new Dictionary<string, string>(); 
    // <key, value> 형태로 데이터 표현

            dict.Add("a", "hi");
        //  dict.Add("a", "hello");  a 라는 키가 이미 존재해서 런타임 에러 발생
            dict.Add("b", "bye");
            dict["a"] = "hello"; 
        // "a" 에 해당하는 키가 없으면 "hello" 값 넣고 키가 있으면 덮어쓰기  
        
        	dict.Add("c", "cc");
            dict.Add("d", "dd");

            string result = dict["a"]; // "a" 에 해당하는 hello

            foreach (var item in dict)
            {
                Console.WriteLine($"value : {item.Key}");
                Console.WriteLine($"value : {item.Value}");
            }

템플릿

 static void TempMethod(int p_val)  //하나의 자료형에만 해당하는 메서드
        {
            int a = p_val;
        }

static void Main(string[] args)
        {

            TempMethod(10);   // 소수나 문자열 입력 불가

            Console.ReadKey();

        }

TempMethod의 매개변수 자료형을 int로 선언하면 int에 해당하는 자료형밖에 사용하지 못함
=> 다양한 자료형으로 메서드를 사용하고 싶을 때 = 템플릿 메서드(T)

 static void TempMethod<T>(T p_val)
        {
            T a = p_val;
        }

static void Main(string[] args)
        {
            TempMethod(10);
            TempMethod(10.5);
            TempMethod("str");

        }

템플릿(T) 사용 시 각자 다른 자료형이여도 동일한 메서드 사용 가능

0개의 댓글