딕셔너리와 누락된 키
Coddy의 R 개발자를 위한 C# 코스 레슨. 48개 중 18번째.
R 리스트에서 존재하지 않는 이름에 대해 [[ ]] 또는 $를 사용하면 NULL이 반환되므로, 이름이 없는 경우에도 오류 없이 넘어갑니다. 또한 $는 부분적으로 일치하는 이름도 찾습니다. 반면 C# Dictionary 인덱서는 KeyNotFoundException을 발생시키며, TryGetValue는 존재 여부를 나타내는 bool과 out 값을 분리합니다. C# 키는 정확히 일치해야 합니다. 대소문자를 구분하는 안정적인 기계 키에는 StringComparer.Ordinal을 선택하세요.
Dictionary<TKey,TValue>는 형식이 지정된 키와 값을 연결합니다. 인덱서로 존재하지 않는 키를 읽으면 예외가 발생합니다. TryGetValue는 존재 여부와 저장된 값을 분리합니다. 대소문자를 구분하는 안정적인 기계 키에는 StringComparer.Ordinal을 선택하세요. toString이라는 키는 그저 키일 뿐입니다.
R 참고 예시
values <- list()
count <- values[["missing"]]
cat(if (is.null(count)) 0 else count, "\n", sep = "")Main 내부의 C# 문
var values = new Dictionary<string,int>();
int count;
Console.WriteLine(values.TryGetValue("missing", out count) ? count : 0);이 예시는 특정 내용을 가르치기 위한 발췌문입니다. 챌린지 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각은 관련된 선언과 문을 보여 줍니다.
참조 출력:
0C# 출력:
0챌린지
쉬움쉼표로 구분된 비어 있지 않은 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);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
R 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 번째 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러