Dynamic Linq Filtering with Parent Property not working

175 Views Asked by At

I have question related to dynamic Linq. I have a class structure defined as below.

    public class UserProfile 
    {
      
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public int Age { get; set; }

        public long Overtime { get; set; }

        public UserProfileDetails UserProfileDetails { get; set; }
    }

    public class UserProfileDetails 
    {
        public UserProfileDetails()
        {
            LstString = new List<string>();
        }
       
        public string Department { get; set; }

        public double Salary { get; set; }

        public int LeaveBalance { get; set; }
        public List<string> LstString { get; set; }
    }

Created a object of UserProfile like given below.

    var a = new UserProfile();

For a normal Linq I can execute the following. I am trying to find all the strings in UserProfileDetails while is not same a my first name.

    var vvv = a.UserProfileDetails.LstString.Where(x => !x.Equals(a.FirstName)).ToList();

I want to convert the above linq to dynamic linq and used the following

     var vDyna = a.UserProfileDetails.LstString.AsQueryable().Where("!Equals(FirstName)").ToList();

But the above is giving the error: System.Linq.Dynamic.Core.Exceptions.ParseException: 'No property or field 'FirstName' exists in type 'String''. Can anyone help me with this please?

1

There are 1 best solutions below

2
On

I think it's similar to the LINQ function. In the where string you have to use the UserProfile variable a. Your Code:

var vDyna = a.UserProfileDetails.LstString.AsQueryable().Where("!Equals(FirstName)").ToList();

My suggestion:

var vDyna = a.UserProfileDetails.LstString.AsQueryable().Where(s => !s.Equals(a.FirstName)).ToList();

I never used Dynamic Linq, but maybe that helps.

Source: https://learn.microsoft.com/en-us/dotnet/api/system.linq.queryable.where?view=net-5.0

EDIT 1:

var vDyna = a.UserProfileDetails.LstString.AsQueryable().Where("!Equals(@0)", a.FirstName).ToList();