Unity 기본6 - C#의 컬렉션 List, Dictionary
1. 컬렉션
하나의 이름으로 여러개의 데이터를 묶어서 관리하는 것
배열과 비슷한데, 크기가 정해져 있지 않다
실시간으로 크기를 변화시킬 수 있다
배열은 다음과 같이 중간에 어디를 제거하면, 나머지 원소들은 그대로 있다
컬렉션은 중간에 원소를 지우면 뒤에 있는 원소가 앞으로 온다
컬렉션에 해당하는 자료구조는..
Dictionary, List, Queue, SortedList, Stack, ArrayList, Hashtable, ...
2. List
List는 배열에 컬렉션으로서의 특징을 더한 형태
배열과는 다르게 개수가 정해져있지 않은 데이터의 목록을 저장하기에 적절
ArrayList와 비슷한데, ArrayList는 저장할 데이터의 타입이 고정이 안된다.
List는 어떤 타입의 데이터를 저장할지 미리 지정하고 사용
마이크로소프트는 ArrayList 사용을 권장하지 않는다
1) 선언
List<string> names;
List하고 <> 안에 저장할 데이터의 타입을 지정
이름만 선언한 상태이고, 빈 공간도 지정해줘야함
List<string> names = new List<string>();
실제로 List가 만들어져서 names라는 이름이 붙는다
다음과 같이
List<string> names = new List<string>(5);로 5개를 지정한다면?
5개 정도 미리 자리를 잡아두는 것
데이터를 하나씩 넣을 때마다 자리를 늘리는 것보다, 미리 어느정도 공간을 잡아두는 것이 효율적
상한선이 아니기 때문에 5개를 넘게 넣어도 공간 크기가 저절로 늘어남
2) Add
names.Add("James");하면 names라는 List에 James라는 원소가 들어감
추가한 순서대로 0번, 1번, 2번, ...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
List<string> names = new List<string>();
names.Add("James");
names.Add("Ari");
Debug.Log(names[0]);
Debug.Log(names[1]);
}
// Update is called once per frame
void Update()
{
}
}
3) Insert
원하는 index에 원소를 삽입할 수 있음
어디에 삽입하느냐에 따라 원래 있던 원소들의 index가 바뀐다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
List<string> names = new List<string>();
names.Add("James");
names.Add("Ari");
names.Insert(0, "Josh");
Debug.Log(names[0]);
Debug.Log(names[1]);
Debug.Log(names[2]);
}
// Update is called once per frame
void Update()
{
}
}
4) Remove
RemoveAt(index);로 index 위치의 원소를 제거
Remove("Ari");로 Ari라는 원소를 제거
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
List<string> names = new List<string>();
names.Add("James");
names.Add("Ari");
names.Insert(0, "Josh");
names.RemoveAt(1);
names.Remove("Ari");
Debug.Log(names[0]);
}
// Update is called once per frame
void Update()
{
}
}
5) Count
names.Count는 names라는 List에 들어있는 원소의 개수
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
List<string> names = new List<string>();
names.Add("James");
names.Add("Ari");
names.Insert(0, "Josh");
names.RemoveAt(1);
names.Remove("Ari");
for (int i = 0; i < names.Count; i++)
{
Debug.Log(names[i]);
}
}
// Update is called once per frame
void Update()
{
}
}
6) Contains
names.Contains("Ari"); 하면 Ari가 names에 들어가 있는가 아닌가?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
List<string> names = new List<string>();
names.Add("James");
names.Add("Ari");
names.Insert(0, "Josh");
names.RemoveAt(1);
names.Remove("Ari");
Debug.Log(names.Contains("Ari"));
}
// Update is called once per frame
void Update()
{
}
}
없으면 False, 있으면 True인듯
7) IndexOf
names.IndexOf(원소);
원소의 index를 구해준다
없는 원소라면 -1이 나옴
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
List<string> names = new List<string>();
names.Add("James");
names.Add("Ari");
names.Insert(0, "Josh");
Debug.Log(names.IndexOf("James"));
Debug.Log(names.IndexOf("Teemo"));
}
// Update is called once per frame
void Update()
{
}
}
8) Clear
List의 모든 원소를 제거
names.clear();
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
List<string> names = new List<string>();
names.Add("James");
names.Add("Ari");
names.Insert(0, "Josh");
names.Clear();
for (int i = 0; i < names.Count; i++)
{
Debug.Log(names[i]);
}
}
// Update is called once per frame
void Update()
{
}
}
3. Dictionary
key - value 저장소
사전을 보면 어떤 단어를 찾을 때,
사랑 : 어떤 사람이나 존재를 몹시 아끼고 귀중히 여기는 마음. 또는 그런 일.
이렇게 단어 : 설명 형태로 나오는데
어떤 "단어"를 통해 그 단어에 해당하는 "설명"을 찾듯이
단어가 key, 설명이 value
key값을 지정해서 value를 저장하는 컬렉션
1) 선언
key의 타입은 문자열을 많이 사용하는데 조건에 맞으면 무엇이든 가능
숫자도 가능함
Dictionary<(key의 타입), (value의 타입)>
Dictionary<string, string> cities = new Dictionary<string, string>();
Dictionary<string, int> cities = new Dictionary<string, int>();
2) Add
cities.Add((key값), (value값));
cities.Add("한국", "서울");하면 key가 한국이고 value가 서울인 원소를 넣는다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Dictionary<string, string> cities = new Dictionary<string, string>();
cities.Add("한국", "서울");
cities.Add("쿠바", "하바나");
cities.Add("칠레", "산티아고");
Debug.Log(cities["한국"]);
}
// Update is called once per frame
void Update()
{
}
}
key - value 형태로 저장하므로, List와 달리 원소의 순서가 없어서,
index로 저장하는 Insert가 없다
2) value값 수정
파이썬처럼 cities["한국"] = "부산";하면 "한국"에 해당하는 value를 수정할 수 있다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Dictionary<string, string> cities = new Dictionary<string, string>();
cities.Add("한국", "서울");
cities.Add("쿠바", "하바나");
cities.Add("칠레", "산티아고");
cities["한국"] = "부산";
Debug.Log(cities["한국"]);
}
// Update is called once per frame
void Update()
{
}
}
처음에 서울이였는데 부산으로 바뀐 것으로 보아,
Dictionary에는 key값이 같은데, value가 서로 다른 원소는 존재할 수 없다
3) ContainsKey, ContainsValue
해당하는 key,value가 존재하는지 검사
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Dictionary<string, string> cities = new Dictionary<string, string>();
cities.Add("한국", "서울");
cities.Add("쿠바", "하바나");
cities.Add("칠레", "산티아고");
Debug.Log(cities.ContainsKey("일본"));
Debug.Log(cities.ContainsValue("하바나"));
}
// Update is called once per frame
void Update()
{
}
}
4) Remove
key값을 삭제할 수 있다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Dictionary<string, string> cities = new Dictionary<string, string>();
cities.Add("한국", "서울");
cities.Add("쿠바", "하바나");
cities.Add("칠레", "산티아고");
cities.Remove("칠레");
Debug.Log(cities["칠레"]);
}
// Update is called once per frame
void Update()
{
}
}
5) Clear
clear로 Dictionary의 모든 key, value를 제거할 수 있다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Dictionary<string, string> cities = new Dictionary<string, string>();
cities.Add("한국", "서울");
cities.Add("쿠바", "하바나");
cities.Add("칠레", "산티아고");
cities.Clear();
Debug.Log(cities["한국"]);
Debug.Log(cities["쿠바"]);
Debug.Log(cities["칠레"]);
}
// Update is called once per frame
void Update()
{
}
}
'프로그래밍 > Unity&C#' 카테고리의 다른 글
Unity 기본8 - C# 사용자 정의 함수 사용법 (0) | 2024.04.22 |
---|---|
Unity 기본7 - foreach, 연습문제 풀기 (0) | 2024.04.21 |
Unity 기본5 - C# 배열에 대해 (0) | 2024.04.19 |
Unity 기본4 - 반복문 while, for문 (0) | 2024.04.18 |
Unity 기본3 - C#의 if와 switch 제어문 (0) | 2024.04.17 |