Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string into a LINQ query

What method would be considered best practice for parsing a LINQ string into a query?

Or in other words, what approach makes the most sense to convert:

 string query = @"from element in source
                  where element.Property = ""param""
                  select element";

into

 IEnumerable<Element> = from element in source 
                        where element.Property = "param"
                        select element;

assuming that source refers to an IEnumerable<Element> or IQueryable<Element> in the local scope.

like image 623
smartcaveman Avatar asked Mar 23 '11 01:03

smartcaveman


People also ask

How to convert string to LINQ query?

How can I convert this string to linq query? string linqstring="(from t1 in Context. Table1 join t2temp in Context. Table2 on t1.Id equals t2.Id into tempJoin from t2 in tempJoin.

What is Dynamic Linq?

The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.


2 Answers

Starting with .NET 4.6 you can use CSharpScript to parse Linq. Assuming the expression you want to parse is in string variable "query", this will do it:

string query = "from element in source where element.Property = ""param"" select element";
IEnumerable result = null;
try 
{
    var scriptOptions = ScriptOptions.Default.WithReferences(typeof(System.Linq.Enumerable).Assembly).WithImports("System.Linq");
    result = await CSharpScript.EvaluateAsync<IEnumerable>(
             query,
             scriptOptions,
             globals: global);
} catch (CompilationErrorException ex) {
//
}

Don't forget to pass your (Data)source you want to work on, with the global-variable(s) to have access to them in script parsing.

like image 133
thewhiteambit Avatar answered Sep 28 '22 09:09

thewhiteambit


It requires some text parsing and heavy use of System.Linq.Expressions. I've done some toying with this here and here. The code in the second article is somewhat updated from the first but still rough in spots. I've continued to mess round with this on occasion and have a somewhat cleaner version that I've been meaning to post if you have any interest. I've got it pretty close to supporting a good subset of ANSI SQL 89.

like image 28
dkackman Avatar answered Sep 28 '22 09:09

dkackman