Parse string into a LINQ query

smartcaveman picture smartcaveman · Mar 23, 2011 · Viewed 13.4k times · Source

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.

Answer

thewhiteambit picture thewhiteambit · Jul 20, 2016

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.