Abdou Telb Abdou Telb - 23 days ago 8
C# Question

Filter in linQ c# with dynamic properties

I have a list of properties

string[] strings =
{
"State", "Name","Location"
};


They are all in Test object with type string, I need to loop throw them first and filter the data when the property equal "OK"

Here is my code snippet

for (int x=0;x<strings.Length;x++)
{
// PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(Test)).Find(strings[x],true);

var miss = _unityOfWork.TestRepository.Get(i =>
i.GetType().GetProperty(strings[x]).Equals("OK") )
.Select().toList()


this code returns the following exception:


"LINQ to Entities does not recognize the method 'System.Reflection.PropertyInfo GetRuntimeProperty(System.Type, System.String)' method, and this method cannot be translated into a store expression."


I need to filter the list with the property name form the array

Answer

Here is how I would probably do it... plain and simple, without reflection, and the switch has two functions: (1) to guard against unknown fields, (2) to apply the proper condition for every case.

var strings = new[] { "State", "Name", "Location" };

var result = _unityOfWork.TestRepository.GetAll().AsQueryable();
// you may need to tweak the above before it works

foreach (var field in strings)
{
    switch (field)
    {
        case "State":
            result = result.Where(x => x.State == "OK");
            break;
        case "Name":
            result = result.Where(x => x.Name == "OK");
            break;
        case "Location":
            result = result.Where(x => x.Location == "OK");
            break;
    }
}

return result;   // if needed, add .ToList() or .ToArray()