2018. 1. 13. 16:20
<List>
리스트는 배열과 유사한 역할을 한다.
List<자료형> 변수명 형태로 선언하며, 객체이므로 new연산자를 꼭 써줘야한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EmptyClass : MonoBehaviour {
List<int> numbers = new List<int> ();//int들어가야하고
List<string> names = new List<string> ();//string들어가야하고
void Start()
{
numbers.Add (1);
numbers.Add (2);
numbers.Add (3);
names.Add ("Carl");
names.Add ("David");
names.Add ("Mancini");
Debug.Log (numbers[1]); //하나씩 볼 수 있다.
Debug.Log (names[1]);
}
} |
<배열과 다른점>
1. 리스트는 크기를 정해줄 필요가 없다.
Add를 사용해 값을 추가할 수 있다. 이때, 추가한 순서대로 리스트에 [x]번째가 된다.
2. Remove를 이용해 언제든지 list의 원하는값을 삭제할 수 있다.
이때, 삭제된 [x]번째보다 뒤에 있는 리스트값은 한칸씩 당겨진다.
3. 배열은 원하는 값이 있는지 확인하기 위해서는 배열의 개수만큼 전부 체크해야 하지만,
리스트는 Contains()를 이용해 원하는 값이 있는지 바로 판단할 수 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // List List< string > list = new List< string >(); // 추가 list.Add( "a" ); list.Add( "b" ); list.Add( "c" ); // 탐색 foreach ( string it in list) { System.Diagnostics.Debug.WriteLine(it); } // 찾기 string key = "키" ; string result = list.Find( delegate ( string data) { return (key == data); } ); if (result != null ) { System.Diagnostics.Debug.WriteLine(result); } |
C#에서 List는 System.Collections.Generic을 추가해야 쓸 수 있다.
List 선언법
List<자료형 또는 클래스> _list = new List<자료형 또는 클래스>();
※ List 또한 객체이기 때문에 꼭 new를 해주자.
주요 메소드 ... (아래 제시된 것 보다 많음)
ⓐ _list.Add() : 원하는 자료를 컨테이너에 삽입 할 수 있다.
ⓑ _list.Remove(자료) : 원하는 자료를 컨테이너에서 삭제할 수 있다.
ⓒ _list.RemoveAt(인덱스) : 원하는 자료를 인덱스 번호로 삭제할 수 있다.
Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List<T>.
지정된 조건자에 정의된 조건과 일치하는 요소를 검색하고 전체 List<T>에서 처음으로 검색한 요소를 반환
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // Find a book by its ID. Book result = Books.Find( delegate (Book bk) { return bk.ID == IDtoFind; } ); if (result != null ) { DisplayResult(result, "Find by ID: " + IDtoFind); } else { Console.WriteLine( "\nNot found: {0}" , IDtoFind); }
|
무명 메서드가 등장하는 이상한(?) 형태를 띄고 있는데..
이는 예제에 대한 설명이다.
IDToFind 조건자 대리자를 사용하여 ID로 책을 찾는다.
IDToFind predicate delegate." xml:space="preserve">C# 예제에서는 익명 대리자를 사용.
즉, 익명 대리자에서 조건을 판별하여 리스트에서 처음으로 검색한 요소를 반환한다는 의미.
간단히 정렬도 가능
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | List< int > sortList = new List< int > (); sortList.Add ( 10 ); sortList.Add ( 3 ); sortList.Add ( 7 ); sortList.Add ( 1 ); sortList.Add ( 4 ); // 정렬 !! sortList.Sort ( delegate ( int a, int b) { return a.CompareTo( b ); }); //이렇게 하면 더 간단함. List< int > sortList = new List< int > (); sortList.Add ( 10 ); sortList.Add ( 3 ); sortList.Add ( 7 ); sortList.Add ( 1 ); sortList.Add ( 4 ); // 알아서 정렬 !! sortList.Sort ();
|