본문 바로가기
카테고리 없음

[코딩일기] C# List

by mania2321 2024. 7. 4.

using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;


public class HelloWorld : MonoBehaviour
{
    void Start()
    {
        List<string> names = new List<string>(5/*효율 차원에서 몇 개의 데이터가 들어갈지 정해주는 것. 이것보다 더 많이 잡으면 또 더 자동으로 늘어남*/);        // new 이 부분이 실제로 리스트를 만듦.

        names.Add("James");
        names.Add("Eric");

        // Debug.Log(names[0]);            // James 출력
        // Debug.Log(names[1]);            // Eric 출력


        // List의 Insert 기능
        names.Insert(0, "John");        // 인덱스 0 자리에 John 삽입. 그럼 John(0), James(1), Eric(2) 순이 됨.
        // names.Clear();               // 기존의 리스트를 날려버림
       
        // Debug.Log(names[0]);            // John 출력
        // Debug.Log(names[1]);            // James 출력
        // Debug.Log(names[2]);            // Eric 출력

        // List의 remove 기능
        // names.RemoveAt(0);              // 인덱스로 삭제할 수 있고,
        // names.Remove("James");          // 데이터 값을 이용한 삭제도 가능하다.

        for(int i = 0; i < names.Count/*names count는 배열의 데이터 개수를 알려줌. 데이터 갯수만큼 i가 늘어남*/; i++)
        {
            Debug.Log("names[" + i + "]" + names[i]);
        }

        // Debug.Log(names.Contains("Eric")/*Contains 는 어떤 내용이 이 List 안에 들어있느냐 고 물어보는 것.*/);       // Eric이 들어있으니 true값이 도출될 것.
                                                                                                                   // 있어선 안될 이름이 있다면 false가 나왔을 것.
        Debug.Log(names.IndexOf("Eric"));       // Eric의 인덱스가 몇 번인가를 묻는 것.
    }
}

댓글