Friday, July 15, 2011

Code kata challenge #2

I've been playing around with linq-like functionality as a code kata the last few days. I've simplified the my Where method and made a simple skip and take function. I can now do this without the actual linq namespace:

var results = list
.Skip(2)
.Take(200)
.Where(x => x % 2 == 0);


My Skip method:

public static IEnumerable<T> Skip<T>(
this IEnumerable<T> list, int count)
{
var enumerator = list.GetEnumerator();
for (var i = 0; i < count; i++)
enumerator.MoveNext();

while (enumerator.MoveNext())
yield return enumerator.Current;
}


My Take method:

public static IEnumerable<T> Take<T>(
this IEnumerable<T> list, int count)
{
var enumerator = list.GetEnumerator();
enumerator.MoveNext();
for (var i = 0; i < count; i++)
{
yield return enumerator.Current;
enumerator.MoveNext();
}
}


My Where method:

public static IEnumerable<T> Where<T>(
this IEnumerable<T> list, Predicate<T> expression)
{
foreach(var item in list)
if(expression(item))
yield return item;
}


It's darned fast too. Delayed excecution rocks.

No comments: