NGMsoftware

NGMsoftware
로그인 회원가입
  • 매뉴얼
  • 학습
  • 매뉴얼

    학습


    C# 21-1. 배열과 컬렉션. (Array, Collection)

    페이지 정보

    본문

    안녕하세요. 소심비형입니다. 정말 오랫만에 적는 글이네요. 요즘 회사일도 바쁘고, 주말에 강의도 2탕이나 뛰고 있어서 여러모로 시간 내기가 쉽지 않군요-_-; 그런데다가 사업을 해볼까 하고 아이디어를 좀 더 구체화하고 있습니다. 하루가 부족하군요. 누군가가 옆에서 좀 도와주면 좋겠지만^^;

     

    오늘은 배열과 컬렉션에 대해서 알아보도록 하겠습니다.

    아래는 정수와 문자열을 담을 수 있는 1차원 배열을 만듭니다. 각각의 배열은 new를 이용하여 선언하며 초기화합니다.

    Program.cs

    using System;
     
    namespace ArrayTest
    {
        class MainApp
        {
            static void Main(string[] args)
            {
                int[] arrayInt = new int[] { 10, 30, 20, 7, 1 };
                string[] arrayString = new string[] { "No", "Good", "Master" };
                Console.WriteLine($"Type of int array : {arrayInt.GetType().Name}");
                Console.WriteLine("Base type of int array : {0}", arrayInt.GetType().BaseType);
                Console.WriteLine($"Type of string array : {arrayString.GetType().Name}");
                Console.WriteLine("Base type of string array : {0}", arrayString.GetType().BaseType);
                Console.ReadKey();
            }
        }
    }
    

     

     

    위 코드를 실행 해보면 아래와 같은 결과를 확인할 수 있습니다. 모든 1차원 배열은 System.Array에서 파생되었다는 것을 알 수 있습니다.

    Pc3d2i6.png

     

     

    이제 배열을 이용하여 평균을 구하는 방법에 대해서 알아보겠습니다.

    Program.cs

    using System;
     
    namespace ArrayTest
    {
        class MainApp
        {
            static void Main(string[] args)
            {
                int[] scores = new int[5];
                scores[0] = 87;
                scores[1] = 74;
                scores[2] = 81;
                scores[3] = 92;
                scores[4] = 66;
                foreach (int score in scores)
                    Console.WriteLine(score);
                int sum = 0;
                foreach (int score in scores)
                    sum += score;
                int average = sum / scores.Length;
                Console.WriteLine($"Average Score : {average}");
                Console.ReadKey();
            }
        }
    }

     

     

    위 코드를 실행 해보면 80이 출력됩니다. 20~21라인에서 합계를 구한 후 23라인과 같이 배열의 길이만큼 나누면 평균을 구할 수 있습니다. 하지만, 좀 더 쉽게 배열에 관련된 여러가지 기능을 사용할 수 있게 도와주는 Linq를 사용하는게 좋습니다. 코드가 명확하고 직관적이기 때문이죠^^;

    아래 코드는 Linq를 사용하여 평균을 구하는 방법을 보여줍니다.

    Program.cs

    using System;
    using System.Linq;
     
    namespace ArrayTest
    {
        class MainApp
        {
            static void Main(string[] args)
            {
                int[] scores = new int[5];
                scores[0] = 87;
                scores[1] = 74;
                scores[2] = 81;
                scores[3] = 92;
                scores[4] = 66;
                foreach (int score in scores)
                    Console.WriteLine(score);
                int sum = 0;
                foreach (int score in scores)
                    sum += score;
                int average = sum / scores.Length;
                average = (int)scores.Average();
                Console.WriteLine($"Average Score : {average}");
                Console.ReadKey();
            }
        }
    }
    

     

     

    위 코드도 결과는 동일합니다. 2라인과 같이 참조를 추가하고, 25라인처럼 링큐(Linq)의 확장 메소드를 이용하여 쉽게 평균을 구할 수 있습니다. 이외에도 아주 많은 메소드들이 존재하지만 일단은 넘어가겠습니다. 언제할지는 모르지만 링큐 관련 글을 쓸 때 자세하게 알아보도록 하겠습니다.

     

    아래 코드는 배열을 초기화 하는 3가지 방법에 대해 보여주고 있습니다.

    Program.cs

    using System;
     
    namespace ArrayTest
    {
        class MainApp
        {
            static void Main(string[] args)
            {
                var br = Environment.NewLine;
                string[] heros1 = new string[3] { "Superman", "Ironman", "Hulk" };
                Console.WriteLine($"배열의 길이를 지정할 경우 초기화 하지 않아도 된다.");
     
                foreach (string hero in heros1)
                    Console.WriteLine(" {0}", hero);
     
                string[] heros2 = new string[] { "Superman", "Ironman", "Hulk" };
                Console.WriteLine($"{br}{br}배열을 생성하면서 초기화 하므로 배열의 길이를 명시하지 않아도 된다.");
     
                foreach (string hero in heros2)
                    Console.WriteLine(" {0}", hero);
     
                string[] heros3 = { "Superman", "Ironman", "Hulk" };
                Console.WriteLine($"{br}{br}배열을 초기화 할 때 생성자를 사용하지 않아도 된다.");
     
                foreach (string hero in heros3)
                    Console.WriteLine(" {0}", hero);
     
                Console.ReadKey();
            }
        }
    }
    

     

     

    배열을 선언 할 때 길이를 지정하면 초기화 하지 않아도 됩니다. 하지만, 배열의 길이를 지정하지 않을 경우에는 반드시 초기화 해야 합니다. 이 때 초기화 하는 값에 따라서 배열의 길이가 정해지기 때문입니다.

    아래는 위 코드를 실행한 결과입니다.

    JezPBeG.png

     

     

    여기까지는 1차원 배열에 대한 내용이었습니다. 이제부터는 다차원 배열의 사용 방법을 알아보고, 배열에 대해 다양한 기능을 사용해 보도록 하겠습니다.

    아래 코드는 2차원 배열을 초기화 하는 3가지 방법을 보여줍니다. 1차원 배열과 크게 다를게 없지만 초기화할 때 중괄호를 중첩해서 사용한다는 부분이 다릅니다.

    Program.cs

    using System;
    namespace ArrayTest
    {
        class MainApp
        {
            static void Main(string[] args)
            {
                int[,] arr = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
     
                for (int i = 0; i < arr.GetLength(0); i++)
                {
                    for (int j = 0; j < arr.GetLength(1); j++)
                    {
                        Console.Write("[{0}, {1}] : {2} ", i, j, arr[i, j]);
                    }
                    Console.WriteLine();
                }
     
                Console.WriteLine();
     
                int[,] arr2 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
     
                for (int i = 0; i < arr2.GetLength(0); i++)
                {
                    for (int j = 0; j < arr2.GetLength(1); j++)
                    {
                        Console.Write("[{0}, {1}] : {2} ", i, j, arr2[i, j]);
                    }
                    Console.WriteLine();
                }
     
                Console.WriteLine();
     
                int[,] arr3 = { { 1, 2, 3 }, { 4, 5, 6 } };
     
                for (int i = 0; i < arr2.GetLength(0); i++)
                {
                    for (int j = 0; j < arr2.GetLength(1); j++)
                    {
                        Console.Write("[{0}, {1}] : {2} ", i, j, arr3[i, j]);
                    }
                    Console.WriteLine();
                }
     
                Console.ReadLine();
            }
        }
    }
    

     

     

    2차원 배열을 응용하면 3차원 배열도 만들 수 있습니다.

    Program.cs

    using System;
    namespace ArrayTest
    {
        class MainApp
        {
            static void Main(string[] args)
            {
                int[,,] array = new int[4, 3, 2] { 
                    { { 1, 2 }, { 3, 4 }, { 5, 6 } }, 
                    { { 1, 4 }, { 2, 5 }, { 3, 6 } }, 
                    { { 6, 5 }, { 4, 3 }, { 2, 1 } }, 
                    { { 6, 3 }, { 5, 2 }, { 4, 1 } }, };
     
                for (int i = 0; i < array.GetLength(0); i++)
                {
                    for (int j = 0; j < array.GetLength(1); j++)
                    {
                        Console.Write("{ ");
                        for (int k = 0; k < array.GetLength(2); k++)
                        {
                            Console.Write("{0} ", array[i, j, k]);
                        }
     
                        Console.Write("} ");
                    }
     
                    Console.WriteLine();
                }
     
                Console.ReadLine();
            }
        }
    }

     

     

    오늘은 간단하게 배열에 대한 내용을 다루어 보았습니다. 아직 알아봐야 할 내용이 많으므로 다음 시간에 이어서 알아보겠습니다.

    다음 시간에...

    • 네이버 공유하기
    • 페이스북 공유하기
    • 트위터 공유하기
    • 카카오스토리 공유하기
    추천0 비추천0

    댓글목록

    등록된 댓글이 없습니다.