I have create a anonymous object list like below.....
List < Object > _dynamicObjectList = new List < Object > ();
for (int i = 0; i < 5; i++) {
_dynamicObjectList.Add(new {
ID = i, Name = "stu" + i, Address = "address234324" + i, DateField = DateTime.Now.AddDays(i)
});
}
Now I need to create string query. My string query is given below..
string searchStr ="it.ID= 1 || it.ID= 2 || it.Name= "stu1" || it.Name= "stu2"";
In the last step I am going to filter my list with the above string...
var returnList= _dynamicObjectList.GetFilteredData(searchStr );
The method which executes Dynamic object is given below...
public static IQueryable GetFilteredData < T > (this IEnumerable < T > source, string searchCriteria) {
if (!string.IsNullOrEmpty(searchCriteria)) {
IList < T > returnList = new List < T > ();
returnList = source.AsQueryable().Where(searchCriteria).ToList();
return returnList.AsQueryable();
} else {
return source.AsQueryable();
}
}
During execution system provide an error
No property or field 'ID' exists in type 'Object'
<T>isObjectbecause you're passing in aList<Object>, and an Object doesn't have the properties on it you're looking for.If your
_dynamicObjectListis declared as a list of those anonymous types then the query can be executed fine, for example if you declare_dynamicObjectListas:More info: A generic list of anonymous class
I think your best bet, if possible, would be to avoid using an anonymous type and just create a class to hold your data.