Skip to content

Instantly share code, notes, and snippets.

@taogawa
Created May 25, 2013 11:09
Show Gist options
  • Select an option

  • Save taogawa/5648722 to your computer and use it in GitHub Desktop.

Select an option

Save taogawa/5648722 to your computer and use it in GitHub Desktop.
Edulinq Part2:Whereまで
using System;
using System.Collections.Generic;
namespace Edulinq
{
public static partial class Enumerable
{
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
return WhereImpl(source, predicate);
}
public static IEnumerable<TSource> WhereImpl<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
foreach (TSource item in source)
{
if (predicate(item))
{
yield return item;
}
}
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections;
using System.Collections.Generic;
// テストにはChainingAssertionも使っている
namespace Edulinq.Tests
{
[TestClass]
public class EnumerableTest
{
[TestMethod]
public void SimpleFiltering()
{
int[] source = { 1, 3, 4, 2, 8, 1 };
var result = source.Where(x => x < 4);
result.Is(1, 3, 2, 1);
}
[TestMethod]
public void NullSourceThrowsNullArgumentException()
{
IEnumerable<int> source = null;
AssertEx.Throws<ArgumentNullException>(() => source.Where(x => x > 5));
}
[TestMethod]
public void NullPredicateThrowsNullArgumentException()
{
int[] source = { 1, 3, 7, 9, 10 };
Func<int, bool> predicate = null;
AssertEx.Throws<ArgumentNullException>(() => source.Where(predicate));
}
[TestMethod]
public void ExecutionIsDeffered()
{
ThrowingEnumerable.AssertDeffered(src => src.Where(x => x > 0));
}
[TestMethod]
public void QueryExpressionSimpleFiltering()
{
int[] source = { 1, 3, 4, 2, 8, 1 };
var result = from x in source
where x < 4
select x;
result.Is(1, 3, 2, 1);
}
}
internal sealed class ThrowingEnumerable : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
throw new InvalidOperationException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
internal static void AssertDeffered<T>(Func<IEnumerable<int>, IEnumerable<T>> deferredFunction)
{
ThrowingEnumerable source = new ThrowingEnumerable();
var result = deferredFunction(source);
using (var iterator = result.GetEnumerator())
{
AssertEx.Throws<InvalidOperationException>(() => iterator.MoveNext());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment