💻 개발
List&Dictionary 사용법
List(리스트)
⭐배열과의 차이
- 선언 : List<type> varName = new List<type>();
List<int> num = new List<int>();
- 원소 추가 : Add(value)
num.Add(2);
... dogs.Add("spaniel"); dogs.Add("beagle"); dogs.Insert(1,"dalmatian");
... dogs.Add("spaniel"); dogs.Add("beagle"); String[] dogs2=new String[3]; dogs2[0]="chiwawa"; dogs2[1]="poodle"; dogs2[2]="pomeranian"; dogs.Insert(1,dogs2);
- 원소 탐색
- Contains(value) : list 안에 해당 요소가 있는지 없는지 여부를 true/false로 반환한다.
if(dogs.Contains("spaniel")){ ...
dogs.IndexOf("spaniel")
String result=dogs.Find(dog=>dog=="chiwawa")
if(dogs.Exist(dog=>dog=="chiwawa")){ ...
- 원소 제거
- Remove(value) : list 내의 value 값을 갖는 요소 제거
- RemoveAt(index) : list의 특정 index의 요소 제거
- RemoveAll() : list 내의 모든 요소 제거
- RemoveRange(startIndex, endIndex) : list 내에서 index 범위 내의 요소들을 제거
- 원소 정렬 : Sort() : 기본적으로 원소들을 오름차순 정렬한다.
Dictionary(딕셔너리)
: 키(key)와 값(value)의 쌍을 원소로 갖는 배열
⭐파이썬의 dictionary와 동일한 개념이다.
- 선언
Dictionary<string, int> dict=new Dictionary<string, int>();
- 원소 추가 : Add(key, value)
dict.Add("cat", 2);
- 원소 값 접근 : dictionary[key]
int val=dict["cat"]
int val1; if(dict.TryGetValue("cat", out val1)){ ... //아래와 같이 변수의 선언과 동시에 값을 받아올 수도 있다. if(dict.TryGetValue("cat", out int val2)){ ...
foreach(var pair in dict){ sum+=**pair.Value**; }
- 키 포함 여부 : ContainsKey(key) 딕셔너리에 존재하는 키인지 여부를 반환한다.
if(dict.ConatinsKey("cat")){ ...
- 딕셔너리의 속성(Property) Count : 딕셔너리의 원소 개수 Keys : 딕셔너리의 키의 배열 Values : 딕셔너리의 값의 배열
Dictionary<string, int> dict=new Dictionary<string, int>(){ {"cat",1}, {"dog",2}, {"rose",1}, {"bird",3} }; **dict.Count //4 dict.Keys //["cat", "dog", "rose", "bird"] dict.Values //[1,2,1,3]**
- 딕셔너리 객체를 복사하는 법 생성자의 인수에 복사하고자 하는 딕셔너리 객체를 입력한다.
Dictionary<string, int> dict2=new Dictionary<string, int>(dict1);
- 딕셔너리를 정렬하는 방법 : LINQ의 OrderBy 메서드를 사용한다.
using System.Linq; ... var sortedDict = dict.OrderBy(x => x.Value); //값을 기준으로 정렬