List 타입 활용하기
using System;
using System.Collections.Generic;
namespace realFinal {
class Program {
static void Main(string[] args) {
List<int> numbers = new List<int>();
List<int> initNumbers = new List<int>() {1, 2, 3, 4, 5, 6};
numbers.Add(1);
numbers.Add(3);
numbers.Add(5);
foreach(var i in numbers) {
Console.Write($"{i} ");
}
}
}
}
Dict 타입 활용하기
using System;
using System.Collections.Generic;
namespace realFinal {
class Program {
static void Main(string[] args) {
IDictionary<string, string> data = new Dictionary<string, string>();
var sameData = new Dictionary<string, string>();
data.Add("apple", "사과");
data.Add("banana", "바나나");
data.Add("grape", "포도");
data.Remove("apple");
data["grape"] = "달달한 포도";
try {
data.Add("grape", "시큼한 포도");
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
foreach (var i in data) {
Console.Write("key : {0}\nvalue : {1} \n\n", i.Key, i.Value);
}
}
}
}
Dict과 TryGetValue() and ContainsKey() 매서드 활용하기
TryGetValue() : Dictionary에 같은 키가 존재할 때, 값을 가져오는 방법
IDictionary<string, string> data = new Dictionary<string, string>();
data.Add("apple", "사과");
data.Add("banana", "바나나");
data.Add("grape", "포도");
if (data.TryGetValue("apple", out var output)){
// 해당 키의 value가 output으로 들어감
Console.WriteLine(output);
}
else {
Console.WriteLine("키 없음");
}
foreach (var i in data) {
Console.Write("key : {0}\nvalue : {1} \n\n", i.Key, i.Value);
}
ContainsKey() : Dictionary에 같은 키가 존재하는지 확인 방법
IDictionary<string, string> data = new Dictionary<string, string>();
data.Add("apple", "사과");
data.Add("banana", "바나나");
data.Add("grape", "포도");
if (!data.ContainsKey("json")) {
data.Add("json", "test");
Console.WriteLine(data["json"]);
}
// 필요에 따라 키 또는 값만 따로 뽑아 출력 가능
var values = data.Values;
foreach (var i in values) {
Console.WriteLine(i);
}
// var keys = data.Keys;
ContainsValue() : Dictionary에 같은 값이 존재하는지 확인 방법
'개발 기록 > C#' 카테고리의 다른 글
[C#] 윈도우 폼 - 체크 박스, 라디오 버튼, 그룹 박스 사용하기 (0) | 2021.12.10 |
---|---|
[C#] 윈도우 폼 - 콤보 박스, 리스트 박스 사용하기 (0) | 2021.12.09 |
[C#] delegate vs 무명 delegate, lamba 란? (0) | 2021.11.22 |
[C# 기본기] out 키워드란? (0) | 2021.10.25 |
댓글