Menu
CoddyTech

딕셔너리와 누락된 키

Coddy의 Ruby 개발자를 위한 C# 코스 레슨. 48개 중 18번째.

Ruby Hash에서 누락된 키를 조회하면 nil 또는 Hash.new(0)에 지정한 기본값이 반환되며, fetch만 KeyError를 발생시킵니다. C# Dictionary 인덱서는 기본값이 없는 fetch처럼 동작합니다. 누락된 키를 읽으면 KeyNotFoundException이 발생합니다. TryGetValue는 키의 존재 여부를 나타내는 bool과 out 값을 분리합니다. Ruby에서는 :pen과 "pen"이 서로 다른 키로 유지됩니다. C# 키에는 선언된 형식이 하나 있으며, StringComparer.Ordinal은 대소문자를 구분하는 규칙을 명시적으로 지정합니다.

Dictionary<TKey,TValue>는 형식이 지정된 키와 값을 연결합니다. 인덱서로 누락된 키를 읽으면 예외가 발생합니다. TryGetValue는 키의 존재 여부와 저장된 값을 분리합니다. 일관되게 대소문자를 구분하는 기계용 키에는 StringComparer.Ordinal을 선택하세요. 인덱서를 통해 쓰면 항목이 추가되거나 대체되지만, 누락된 키를 증가시키려면 먼저 해당 키를 읽어야 합니다.

Ruby 참고 코드

counts = Hash.new(0)
counts["pen"] += 1
puts counts["missing"]
puts counts["pen"]
puts counts.key?("missing")

Main 내부의 C# 문장

var counts = new Dictionary<string, int>(StringComparer.Ordinal);
int count;
counts.TryGetValue("pen", out count);
counts["pen"] = count + 1;
Console.WriteLine(counts.TryGetValue("missing", out count) ? count : 0);
Console.WriteLine(counts["pen"]);
Console.WriteLine(counts.ContainsKey("missing"));

이 내용은 특정 개념을 설명하기 위한 발췌문입니다. 챌린지 파일에는 완전히 실행 가능한 래퍼 코드가 포함되어 있으며, 위 스니펫은 관련 선언과 문장만 보여 줍니다.

Ruby 출력:

0
1
false

C# 출력:

0
1
False
challenge icon

챌린지

쉬움

쉼표로 구분된 비어 있지 않은 ASCII 단어들을 입력하거나, 단어가 없으면 빈 줄을 입력한 다음 조회 키를 입력하세요. 키와 대소문자가 정확히 일치하는 항목의 개수를 세세요. 없는 키는 0을 반환합니다.

잠금 해제된 C# 파일을 수정하세요. 잠긴 상태로 표시된 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하며, 입력이 변경되지 않았는지 확인한 뒤 마지막에 줄바꿈을 하나 붙여 결과를 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 인쇄하지 마세요.

직접 해보기

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Words(input[0]); string before0=Snapshot(a0);
var a1 = input[1]; string before1=Snapshot(a1);

var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Ruby 개발자를 위한 C#의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러