C# List (C#의 Generic Collection의 한 종류)

m._.jooong·2023년 3월 14일
0

Unity C#

목록 보기
18/22
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// C# 자료구조 라이브러리 Generic Collection
// C#의 Generic Collection 중 List

public class Test_1 : MonoBehaviour
{
    // 정렬 조건 함수
    int Comp(int a, int b)
    {
        return a.CompareTo(b); // 오름차순(ASC) : 낮은 값에서 높은 값으로 정렬(1, 2, 3, 4, ...)

        //return -a.CompareTo(b); // 내림차순(DESC) : 높은 값에서 낮은 값으로 정렬(10, 9, 8, 7, ...)
    }

    // Start is called before the first frame update
    void Start()
    {
        // --- List 사용법
        List<int> a_List = new List<int>();

        Debug.Log("<노드 추가하기>");
        a_List.Add(111);
        a_List.Add(222);
        a_List.Add(333);

        for (int ii = 0; ii < a_List.Count; ii++)
        {
            Debug.Log(a_List[ii]);
        }

        Debug.Log("------------------");
        a_List.Add(444);
        a_List.Add(555);
        //for(int ii = 0; ii<a_List.Count; ii++)
        //{
        //    Debug.Log(a_List[ii]);
        //}
        foreach(int val in a_List)
        {
            Debug.Log(val);
        }

        Debug.Log("<노드 제거하기>");
        a_List.RemoveAt(1); // 1번 인덱스 제거 방법
        for(int ii = 0; ii<a_List.Count; ii++)
        {
            Debug.Log("["+ ii+ "] : " +a_List[ii]);      // 111, 333, 444, 555
        }

        Debug.Log("<중간값 추가>");
        a_List.Insert(1, 10);
        a_List.Insert(3, 30);
        int a_idx = 0;
        foreach(int val in a_List)
        {
            Debug.Log("a_list[ " + a_idx + "] : " + val);
            a_idx++;
        }

        Debug.Log("<정렬하기>");
        //a_List.Sort();      // 오름차순(ASC) : 낮은 값에서 높은값으로 정렬
        //a_List.Reverse();   // 순서를 뒤집는 함수 --> 내림차순(DESC) : 높은값에서 낮은값으로 정렬
        a_List.Sort(Comp);

        foreach(int val in a_List)
        {
            Debug.Log(val);
        }


    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

0개의 댓글