TIL. 189 [C#] List에 Array(배열) 또는 List 저장 하는 방법

조윤식·2022년 9월 23일
0

이번 포스팅에서는 C# 컬렉션 중 하나인 List에서 단순히 값을 추가하는 것이 아닌, List에 Array(배열) 또는 List를 저장 하는 방법에 대해서 알려드리도록 하겠습니다.

해당 부분을 알게 되면, 매우 유용하게 쓰일 수 있다고 생각하기 때문에 알아두시면 좋겠습니다.^^

먼저 C# 콘솔프로그램을 생성하여 주시고,

아래와 같이 코드를 작성해 주시기 바랍니다.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Test

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("단순 List에 해당 값 Add 메서드로 추가");

            ListAdd();

            Console.WriteLine();

            Console.WriteLine("List에 Array(배열) 또는 List 추가");

            ListAddRange();

 

 

        }

 

        /// <summary>

        /// 단순히 List에 해당 값 추가

        /// </summary>

        private static void ListAdd()

        {

            //list 객체 선언

            List<int> list = new List<int>(); 

 

            for(int i = 0; i < 10; i++)

            {

                //i = 0, 1, 2...9 까지 list 추가

                list.Add(i);

            }

 

            foreach(int i in list)

            {

                Console.WriteLine("List 값 = {0}", i);

            }

            

        }

 

        /// <summary>

        /// List에 Array(배열) 또는 List 추가

        /// </summary>

        private static void ListAddRange()

        {

            List<int> list = new List<int>();

 

            for (int i = 0; i < 10; i++)

            {

                //i = 0, 1, 2...9 까지 list 추가

                list.Add(i);

            }

 

            int[] array = { 12, 43, 65 };

 

            //배열 또는 List 추가 할 때에는, AddRange에 추가

            list.AddRange(array); 

 

            foreach (int i in list)

            {

                Console.WriteLine("List 값 = {0}", i);

            }

        }

    }

}

보기 좋게 처음에는 단순히 List에 값을 추가하는 Add 메서드 사용해 출력하는 부분을 코드로 작성하였고,

다음으로는 AddRange 메서드를 이용해 List에 Array(배열)을 추가하여 출력하는 코드를 작성하였습니다.

이미 위에서 주석으로 코드에 대한 설명은 하였기 때문에,

따로 코드 설명은 하지 않겠습니다. (매우 간단합니다..ㅎㅎ)

profile
Slow and steady wins the race

0개의 댓글

관련 채용 정보