Filter anonymous object list by executing string clause in where condition

c# dynamic-linq linq

Question

DOTNETFIDDLE

I've created a list of anonymous objects like the one 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)
    });
}

I must now build a string query. The string query I used is below.

string searchStr ="it.ID= 1 || it.ID= 2 || it.Name= "stu1" || it.Name= "stu2"";

I'm going to use the aforementioned string to filter my list in the last step.

var returnList= _dynamicObjectList.GetFilteredData(searchStr );

The following technique is used to run a dynamic object.

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();
    }

}

The system provides an error during execution.

No property or field 'ID' exists in type 'Object'

1
2
6/25/2015 5:33:40 AM

Popular Answer

<T> is Object when you're traveling in aList<Object> , and an Object lacks the attributes you're seeking for.

When your_dynamicObjectList the query may be successfully run if it is expressed as a list of those anonymous types, for example if you declare_dynamicObjectList as:

var _dynamicObjectList = new[] {
            new {ID = 0, Name = "stu" + 0, Address = "address234324" + 0, DateField = DateTime.Now.AddDays(0)},
            new {ID = 1, Name = "stu" + 1, Address = "address234324" + 1, DateField = DateTime.Now.AddDays(1)},
            new {ID = 2, Name = "stu" + 2, Address = "address234324" + 2, DateField = DateTime.Now.AddDays(2)},
            new {ID = 3, Name = "stu" + 3, Address = "address234324" + 3, DateField = DateTime.Now.AddDays(3)},
            new {ID = 4, Name = "stu" + 4, Address = "address234324" + 4, DateField = DateTime.Now.AddDays(4)},
        }.ToList();

Information: a list of anonymous classes in general

Your best option, in my opinion, would be to just construct a class to house your data instead of utilizing an anonymous type.

2
5/23/2017 10:26:43 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow