Yield return & using IDisposable

Deutsche Version

“Yield return” is a powerful and handy statement if you want to quickly and easily an iteratable list without creating an Array or a List first:

using System;
using System.Collections.Generic;
using System.Drawing;

class Program
{
    static void Main()
    {
        var colors = Rainbow;

        Console.WriteLine("colors.GetType(): {0}", colors.GetType());
        Console.WriteLine();

        foreach (Color color in colors)
        {
            Console.WriteLine(color.Name);
        }

        Console.ReadLine();
    }

    static IEnumerable<Color> Rainbow
    {
        get
        {
            yield return (Color.Red);
            yield return (Color.Orange);
            yield return (Color.Yellow);
            yield return (Color.Green);
            yield return (Color.LightBlue);
            yield return (Color.Indigo);
            yield return (Color.Violet);
        }
    }
}
Red
Orange
Yellow
Green
LightBlue
Indigo
Violet

The .NET compiler then creates the necessary IEnumerable- and IEnumerator-implementing classes and the state machine in the background and everything is fine and clear.
Read more

Linq: Split()

Deutsche Version

Terminator T1000

So you know the Cinderella saying “The good ones go into the pot, the bad ones go into your crop.”?

Well, .NET Linq does have a solution for either one, it’s called Where(). If you use that, your solution probably looks like this:

var evens = list.Where(number => ((number % 2) == 0));
var odds =  list.Where(number => ((number % 2) != 0));

But it does not have a solution for both. So I wrote myself one:

public static void Split<T>(this IEnumerable<T> source
    , Func<T, Boolean> predicate
    , out IEnumerable<T> trueList
    , out IEnumerable<T> falseList)
{
    trueList = source.Where(predicate);
    falseList = source.Except(trueList);
}

Read more