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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With