public
anonymous / gist:1030248
Created

WhereEnumerable

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
 
using Linq = System.Linq;
 
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
var s =
Linq.Enumerable.Range(1, 200)
.Where(x => x > 50)
.Where(x => x < 100);
var r = Linq.Enumerable.ToList(s);
}
}
 
class PredicateHolder<T>
{
private Func<T, bool> predicate;
private PredicateHolder<T> next;
public PredicateHolder(Func<T, bool> predicate, PredicateHolder<T> next = null)
{
this.predicate = predicate;
this.next = next;
}
 
public bool Eval(T x)
{
var ok = true;
var holder = this;
while (ok && holder != null)
{
ok &= holder.predicate(x);
holder = holder.next;
}
return ok;
}
}
 
class WhereEnumerable<T> : IEnumerable<T>
{
private IEnumerable<T> source;
private PredicateHolder<T> holder;
public WhereEnumerable(IEnumerable<T> source, PredicateHolder<T> holder)
{
this.source = source;
this.holder = holder;
}
 
public WhereEnumerable<T> Where(Func<T, bool> extraPredicate)
{
return new WhereEnumerable<T>(source, new PredicateHolder<T>(extraPredicate, holder));
}
 
public IEnumerator<T> GetEnumerator()
{
foreach (var item in source)
{
if (holder.Eval(item))
yield return item;
}
}
 
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
 
 
}
 
static class Extensions
{
public static IEnumerable<T> Where<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
{
var whereEnumerable = enumerable as WhereEnumerable<T>;
return whereEnumerable != null
? whereEnumerable.Where(predicate)
: new WhereEnumerable<T>(enumerable, new PredicateHolder<T>(predicate));
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.