任意の型に対してLINQのクエリ式を使用する

知らなかったよ。自分で作った任意の型にクエリ式が使えるんですね。

[TestClass]
public class LinqTest{
[TestMethod]
public void Test()
{
var source = new Wrapper<int>(100);

var wrapper =
from n in source
where n > 50
select n;
Assert.AreEqual(100, wrapper.Value);

var wrapper2 =
from n in source
where n > 100
select n;
Assert.AreEqual(0, wrapper2.Value);
}
}

public class Wrapper<T>
{
public T Value { get; private set; }

public Wrapper(T value)
{
Value = value;
}
}

public static class WrapperExtensinos{
public static Wrapper<R> Select<T, R>(this Wrapper<T> source, Func<T, R> selector)
{
return new Wrapper<R>(selector(source.Value));
}

public static Wrapper<T> Where<T>(this Wrapper<T> source, Func<T, bool> predicate)
{
if (predicate(source.Value))
{
return source;
}
return new Wrapper<T>(default(T));
}
}