2017/11/28

C# yield return, 확장 메서드를 이용하여 Enumerable.Where 만들기

Enumerable.Where 와 같은 동작을 하는 Where2 를 만들어 보자.

public static class EnumerableEx
{
    public static IEnumerable<TSource> Where2<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        foreach (var item in source)
        {
            if (predicate(item))
                yield return item;
        }
    }
}

확장 메서드로 만들어서 IEnumerable.Where2 로 사용 가능하며
yield return 으로 지연 반환을 한다.


List<int> list = new List<int>();

list.Add(1);
list.Add(2);
list.Add(3);

var result = list.Where2(i => i > 1);

foreach (var item in result) { }//result 2, 3

list.Add(4);

foreach (var item in result) { }//result 2, 3, 4

C# async await 를 이용한 안전한 WinForm Control 호출

Button을 클릭 하면 어떤 작업을 실행하고 실행 과정을 ProgressBar에 표시 한다고 가정하자.

이전 사용하던 번거로운 비동기 처리 작업과 Control.Invoke() 메서드를 사용하지 않고
async await 를 사용하여 간편하게 비동기 처리가 가능 하다.


private async void button1_Click(object sender, EventArgs e)
{
    int taskCount = 10;

    this.progressBar1.Minimum = 0;
    this.progressBar1.Maximum = taskCount;
    this.progressBar1.Value = 0;

    for (int i = 0; i < taskCount; i++)
    {
        await this.SometingAsync();

        this.progressBar1.Value++;
    }
}

private async Task SometingAsync()
{
    await Task.Delay(2000);
}

C# 문자열 포함 여부 확인하기.

ToUpper() 를 사용하면 불필요한 문자열을 생성하므로 좋은 방법은 아니다. string text = "This is an apple." ; string apple = "Apple." ; bool ...