Abdou Telb Abdou Telb - 1 year ago 112
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") )

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 Source

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");
        case "Name":
            result = result.Where(x => x.Name == "OK");
        case "Location":
            result = result.Where(x => x.Location == "OK");

return result;   // if needed, add .ToList() or .ToArray() 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download