Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Dynamic ParseLambda not resolving

Tags:

c#

asp.net

linq

I'm trying to use the sample code I found here for something i'm working on: How to convert a String to its equivalent LINQ Expression Tree?

In the solution the author uses the following:

var e = DynamicExpression.ParseLambda(new[] { p }, null, exp);

However, whenever I try to use it, it does not resolve. I get an error:

System.Linq.Expressions.DynamicExpression' does not contain a definition for 'ParseLambda'

I installed the System Linq Dynamic nuget package in the project, I've also added a using statement:

using System.Linq.Dynamic;

However, that appears greyed out so i'm guessing it's not picking up that the DynamicExpression object i'm referring to is from there, it's picking it up from System.Linq.Expression instead. Is there a way to fix this? I've tried making it

System.Linq.Dynamic.ParseLambda(new[] { p }, null, tagCondition);

but still no good, same error and the using statement is still greyed out.

like image 798
Paritosh Avatar asked Oct 16 '15 18:10

Paritosh


2 Answers

The assemblies

System.Linq.Dynamic;
System.Linq.Expressions;

both contain DynamicExpression. Since you need both of these, you will need to either give an alias to System.Linq.Dynamic or explicitly as System.Linq.Dynamic.DynamicExpression

You need to make sure you install System.Linq.Dynamic using the package manager.

A full minimally working example is here:

using System.Linq.Expressions;
using myAlias = System.Linq.Dynamic;

namespace ConsoleApplication11
{
    public class Foo
    {
        public string Bar { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var expression = @"(Foo.Bar == ""barbar"")";
            var p = Expression.Parameter(typeof(Foo), "Foo");
            var e = myAlias.DynamicExpression.ParseLambda(new[] { p }, null, expression);

            var test1 = new Foo()
            {
                Bar = "notbarbar",

            };

            var test2 = new Foo()
            {
                Bar = "barbar"
            };

            // false
            var result1 = e.Compile().DynamicInvoke(test1);

            // true
            var result2 = e.Compile().DynamicInvoke(test2);
        }
    }
}
like image 179
Leigh Shepperson Avatar answered Sep 27 '22 18:09

Leigh Shepperson


To resolve this I ended up grabbing the Dynamic.cs file from here: https://msdn.microsoft.com/en-us/vstudio/bb894665.aspx?f=255&MSPPError=-2147217396 I added that to my solution and used it, in this one the DynamicExpression class was public so i was found.

like image 27
Paritosh Avatar answered Sep 27 '22 19:09

Paritosh