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'
An easy way to initialize your list is using Enumerable.Range and anonymous type:
Regardless of the way you initialize it, I see two major problems with your
GetFilteredData
method though:IEnumeration<object>
or usedynamic
type, which totally defeats the purpose of your anonymous type.searchCriteria
to a some sort list of criteria, before it can be applied to your collection. Depending on the allowed syntax, it could be a simple or not so simple task. When you get the parser, then you you'll need write an extension.Where
method which acceptsstring
as criteria.You'll make your life easier if you define a regular type for your collection and clarify what the filtering criteria should be. Based on your example they could two simple lists - one for IDs, and another one for Names. Then you can parse your string into those two collections and then use those collection to filter your original list.