티스토리 뷰
개인사정상 9시부터 12시까지 수업을 듣지 못하고 오후 수업만 들었다..
아마도? 이제 C#의 기본적인 내용들은 거의 다 나간 것 같다
💻 C#
List
var names = new List<string> { "Alice", "Bob", "Charlie" };
names.Add("Dave");
names.Remove("Bob");
foreach (var name in names)
{
Console.WriteLine(name); // Alice Charlie Dave
}
Console.WriteLine();
names.Insert(1, "Jolie");
foreach (var name in names)
{
Console.WriteLine(name); // Alice Jolie Charlie Dave
}
Stack
var stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
while(stack.Count > 0)
{
Console.Write($"{stack.Pop()} "); // 3 2 1
}
Queue
var queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
while (queue.Count > 0)
{
Console.Write($"{queue.Dequeue()} "); // 1 2 3
}
ArrayList
var arrayList = new ArrayList();
arrayList.Add(1);
arrayList.Add("Hello");
arrayList.Add(3.14);
foreach(var item in arrayList)
{
Console.Write(item + " "); // 1 Hello 3.14
}
Console.WriteLine(0);
arrayList.Remove(1);
foreach (var item in arrayList)
{
Console.Write(item + " "); // Hello 3.14
}
요즘은 거의 쓰지 않고 List를 쓴다
Hashtable
var hashtable = new Hashtable();
hashtable["Alice"] = 25;
hashtable["Bob"] = 30;
hashtable["포션"] = 20;
foreach(DictionaryEntry entry in hashtable)
{
Console.WriteLine($"{entry.Key}: {entry.Value} ");
}
Console.WriteLine($"\\nAlice의 나이: {hashtable["Alice"]}\\n");
hashtable.Remove("Bob");
foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine($"{entry.Key}: {entry.Value} ");
}
key-value 를 저장하는 컬렉션이다. key를 이용해 값을 빠르게 검색한다
요즘은 거의 쓰지 않고 Dictionary를 쓴다
Generic
class Cup<T>
{
public T Content { get; set; }
}
Cup<string> cupOfString = new Cup<string> { Content = "Coffee" };
Cup<int> cupOfInt = new Cup<int> { Content = 42 };
Console.WriteLine($"CupOfString: {cupOfString.Content}");
Console.WriteLine($"cupOfInt: {cupOfInt.Content}");
Generic의 장점
✅ **타입 안정성(Type Safety)**→ 잘못된 타입이 들어가는 것을 컴파일 단계에서 방지
✅ 형 변환(Casting) 불필요 → object 기반 컬렉션보다 성능이 향상됨
✅ 코드 재사용성 증가 → 한 번의 구현으로 여러 타입에서 사용 가능
Enumerate
ArrayList list = new ArrayList { "Apple", "Banana", "Cherry" };
IEnumerator enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
Console.Write(enumerator.Current + " ");
}
컬렉션의 내부 구조를 몰라도 안전하게 요소를 순회할 수 있다
foreach 는 내부적으로 Enumerator를 사용하여 컬렉션을 순환한다
Dictionary
var dict = new Dictionary<string, int>();
dict["금도끼"] = 10;
dict["은도끼"] = 5;
dict["돌도끼"] = 1;
foreach(var pair in dict)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
null값
string text = null;
if (text == null)
{
Console.WriteLine("값이 없습니다.");
}
int length = text?.Length ?? 0;
Console.WriteLine(length); // 0
int? age = null;
double? price = null;
if (age.HasValue)
{
Console.WriteLine($"나이: {age.Value}");
}
else
{
Console.WriteLine("나이가 설정되지 않음.");
}
C#에서 참조 타입은 null을 가질 수 있지만, 값 타입은 nullable을 사용하여 가질 수 있다
null 관련 주요 연산자
연산자 | 설명 | 예제 |
== null | null인지 비교 | if (name == null) { ... } |
?. | null이면 null을 반환 | int? length = text?.Length; |
?? | null이면 기본값 설정 | int length = text?.Length ?? 0; |
??= | null이면 해당 값 할당 | text ??= "기본값"; |
LINQ
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNums = nums.Where(n => n % 2 == 0);
foreach(var num in evenNums)
{
Console.Write(num + " "); // 2 4 6 8 10
}
데이터를 조회(Query)하는 기능으로 Array, List 등 다양한 데이터 소스에 사용 가능하다
LINQ 주요 연산자
연산자 | 설명 | 예제 |
Where | 조건에 맞는 요소 필터링 | list.Where(x => x > 10) |
Select | 데이터를 변환 | list.Select(x => x * 2) |
OrderBy | 오름차순 정렬 | list.OrderBy(x => x) |
OrderByDescending | 내림차순 정렬 | list.OrderByDescending(x => x) |
GroupBy | 그룹화 | list.GroupBy(x => x.Category) |
Join | 두 개의 컬렉션 결합 | list1.Join(list2, x => x.Id, y => y.Id, (x, y) => new { ... }) |
FirstOrDefault | 첫 번째 요소 반환 (없으면 null) | list.FirstOrDefault(x => x > 10) |
Sum | 합계 계산 | list.Sum(x => x.Price) |
Count | 개수 반환 | list.Count(x => x > 10) |
예제
var squares = numbers.Select(n => n * n); // 변환
foreach (var num in squares)
{
Console.WriteLine(num); // 출력: 1, 4, 9, 16, 25
}
List<string> names = new List<string> { "Charlie", "Alice", "Bob" };
var sortedNames = names.OrderBy(n => n); // 오름차순 정렬
foreach (var name in sortedNames)
{
Console.WriteLine(name); // Alice, Bob, Charlie
}
📝 과제
배운 내용 복습
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AssignmentDay8
{
class Warrior
{
public string Name { get; set; }
public int Score { get; set; }
public int Strength { get; set; }
public Warrior()
{
Name = "";
Score = 0;
Strength = 0;
}
public Warrior(string name, int score, int strength)
{
Name = name;
Score = score;
Strength = strength;
}
}
class Program
{
static void Main(string[] args)
{
// 과제 1
var warrior = new Warrior("홍길동", 80, 96);
Console.WriteLine("Name\\tScore\\tStrength");
Console.WriteLine($"{warrior.Name}\\t{warrior.Score}\\t{warrior.Strength}");
// 과제 2
Console.Write("숫자를 입력하세요: ");
try
{
var input = Console.ReadLine();
var num = int.Parse(input);
Console.WriteLine($"{num}을 입력했습니다.");
}
catch (FormatException)
{
Console.WriteLine("올바른 숫자를 입력하세요.");
}
// 과제3
var fruits = new List<string>();
fruits.Add("사과");
fruits.Add("바나나");
fruits.Add("포도");
foreach (var fruit in fruits)
{
Console.Write(fruit + " ");
}
Console.WriteLine();
var queue = new Queue<string>();
queue.Enqueue("첫번째작업");
queue.Enqueue("두번째작업");
queue.Enqueue("세번째작업");
while (queue.Count > 0)
{
Console.Write(queue.Dequeue() + " ");
}
Console.WriteLine();
var stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
while (stack.Count > 0)
{
Console.Write(stack.Pop() + " ");
}
Console.WriteLine();
// 과제4
Console.Write("문장을 입력하세요: ");
var input2 = Console.ReadLine();
var upperInput = input2.ToUpper();
Console.WriteLine(upperInput);
var replacedInput = input2.Replace("C#", "CSharp");
Console.WriteLine(replacedInput);
Console.WriteLine(input2.Length);
// 과제5
var nums = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNums = nums.Where( n => n % 2 == 0 );
foreach(var n in evenNums)
{
Console.Write(n + " ");
}
Console.WriteLine();
var sum = nums.Sum();
Console.WriteLine(sum);
}
}
}
'Unity > 멋쟁이사자처럼' 카테고리의 다른 글
멋쟁이 사자처럼 부트캠프 유니티 게임 개발 4기 10일차 회고 (0) | 2025.03.07 |
---|---|
멋쟁이 사자처럼 부트캠프 유니티 게임 개발 4기 9일차 회고 (0) | 2025.03.07 |
멋쟁이 사자처럼 부트캠프 유니티 게임 개발 4기 7일차 회고 (0) | 2025.03.07 |
멋쟁이 사자처럼 부트캠프 유니티 게임 개발 4기 6일차 회고 (0) | 2025.03.07 |
멋쟁이 사자처럼 부트캠프 유니티 게임 개발 4기 5일차 회고 (0) | 2025.03.07 |