Machineboy空
Exercism - Strain: 제너릭 메소드, 델리게이트, yield return 본문
문제요약
조건에 맞는 요소를 출력하라.
https://exercism.org/tracks/csharp/exercises/strain
Strain in C# on Exercism
Can you solve Strain in C#? Improve your C# skills with support from our world-class team of mentors.
exercism.org
난이도
Easy
풀이 포인트
- 델리게이트 이해
- IEnumerable 형 특징 이해

REVIEW
우선 파라미터에 들어가 있는 델리게이트 함수의 이름을 처음에 발견하지 못해 헤맸다.
그리고 아직 IEnumerable형의 lazy 실행에 관해 익숙하지 않아서,
List를 생성하고 조건에 맞는 값을 넣은 뒤 출력하는 방식으로 구현했는데,
IEnumerable의 장점인 yield를 사용하여 필요할 때마다 생성을 요청한다면,
메모리 관리차원과 가독성 상으로도 깔끔한 코드가 가능하니 익혀두자.
풀이 자체는 간단하지만, 다양한 문법이 사용되어 있어 공부하기 좋았던 문제.
CODE
using System;
using System.Collections.Generic;
public static class Strain
{
public static IEnumerable<T> Keep<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
List<T> list = new List<T>();
foreach(T t in collection)
{
if(predicate(t)) list.Add(t);
}
return list.ToArray();
}
public static IEnumerable<T> Discard<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
foreach(T t in collection)
{
if(!predicate(t)) yield return t;
}
}
}
'Computer > CS' 카테고리의 다른 글
[From Nand to Tetris] 모듈 5. Machine Language (0) | 2025.02.10 |
---|---|
[From Nand to Tetris] Project 3 : Bit, Register, RAM8, RAM64, RAM512, RAM4K, RAM16K, PC (0) | 2025.02.04 |
[From Nand to Tetris] 모듈 3. Memory (0) | 2025.02.03 |
[From Nand to Tetris] Project 2 - HalfAdder, FullAdder, Add16, Inc16, ALU (0) | 2025.01.23 |
[From Nand to Tetris] 모듈 2.Boolean Arithmetic and the ALU (0) | 2025.01.22 |