Skip to content

Instantly share code, notes, and snippets.

@vietnt
Created March 5, 2012 16:36
Show Gist options
  • Save vietnt/1979169 to your computer and use it in GitHub Desktop.
Save vietnt/1979169 to your computer and use it in GitHub Desktop.
linq_functions
public class LinqQuery<T>
{
Action<Action<T>> _source;
public LinqQuery(Action<Action<T>> source)
{
_source = source;
}
public LinqQuery(T[] array)
{
_source = (act) =>
{
for (var i = 0; i < array.Length; i++) act(array[i]);
};
}
public LinqQuery(IList<T> list)
{
_source = (act) =>
{
for (var i = 0; i < list.Count; i++) act(list[i]);
};
}
public LinqQuery<T> Where(Func<T, bool> f)
{
var pre = _source;
_source = (act) => pre(item => { if (f(item)) act(item); });
return this;
}
public LinqQuery<TR> Select<TR>(Func<T, TR> f)
{
return new LinqQuery<TR>(act => _source(item => act(f(item))));
}
public IList<T> ToList()
{
var list = new List<T>();
_source(list.Add);
return list;
}
}
public static class Linq
{
public static LinqQuery<T> Where<T>(this IList<T> list, Func<T, bool> f)
{
return new LinqQuery<T>(list).Where(f);
}
public static LinqQuery<TR> Select<T,TR>(this IList<T> list, Func<T,TR> f)
{
return new LinqQuery<T>(list).Select(f);
}
}
// test
// var list = new List<int>{1,2,3,4}
// list.Where(i=>i%2==0).Select(i*i).ToList(); // 4,16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment