Skip to content

Instantly share code, notes, and snippets.

@chakrit
Created October 26, 2010 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chakrit/648031 to your computer and use it in GitHub Desktop.
Save chakrit/648031 to your computer and use it in GitHub Desktop.
Some of the best features that came with LINQ that isn't related to databases.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace DummyConsole
{
internal unsafe class Program
{
public static void Main(string[] args) { (new Program()).Run(); }
public void Run()
{
Console.Write("Enter condition: ");
var predicate = predicatize(Console.ReadLine());
Console.Write(" Understood as: ");
Console.WriteLine(predicate.ToString());
Console.WriteLine("Displaying the first 10 results:");
var results = fib()
.AsParallel()
.Where((_, idx) => idx < 10000) // limit search space
.Where(predicate.Compile())
.Take(10);
foreach (var num in results)
Console.WriteLine(num);
Console.WriteLine("Done.");
Console.ReadKey();
}
private IEnumerable<int> fib()
{
int a = 0, b = 1;
while (true)
yield return a = b + (b = a);
}
private Expression<Func<int, bool>> predicatize(string str)
{
var arg = Expression.Parameter(typeof(int), "n");
return Expression.Lambda<Func<int, bool>>(predicatizeCore(str, arg), arg);
}
private Expression predicatizeCore(string str, Expression arg)
{
var idx = -1;
Func<string, Func<Expression, Expression, Expression>, Expression> binOps =
(op, builder) =>
(idx = str.IndexOf(op)) > -1 ? builder(
predicatizeCore(str.Substring(0, idx), arg),
predicatizeCore(str.Substring(idx + op.Length), arg)) :
null;
return string.IsNullOrEmpty(str = str.Trim()) ? Expression.Constant(false) :
char.IsNumber(str[0]) ? Expression.Constant(int.Parse(str)) : (
binOps("&&", Expression.And) ??
binOps("||", Expression.Or) ??
binOps("<", Expression.LessThan) ??
binOps(">", Expression.GreaterThan) ??
binOps("==", Expression.Equal) ??
binOps("!=", Expression.NotEqual) ??
arg);
}
}
}
Enter condition: n < 8 || n > 100000 && n != 1
Understood as: n => (((n < 8) Or (n > 100000)) And (n != 1))
Displaying the first 10 results:
2
3
5
121393
196418
317811
514229
832040
1346269
2178309
Done.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment