How to create dynamic-linq where for a List of Dictionary?

c# dynamic-linq

Question

I've been using dynamic-linq to filter a list of object using a simple Where clause:

public class Employee
{
    public int Age = 0;
    public string FirstName = "";
}

var list1 = new List<Employee>();
for (int i = 0; i < 100; i++)
{
    list1.Add(new Employee()
    {
        Age = i,
        FirstName = "FirstName-" + i
    });
}
IQueryable<Employee> queryable1 = list1.AsQueryable();
IQueryable<Employee> result1 = queryable1.Where("Age==3");

The code above is working but now I have to apply the same logic on a List of Dictionary:

public class EmployeeDictionary : Dictionary<string, object>
{

}

var list2 = new List<EmployeeDictionary>();
for (int i = 0; i < 100; i++)
{
    var employeeDictionary = new EmployeeDictionary();

    employeeDictionary["Age"] = i;
    employeeDictionary["FirstName"] = "FirstName-" + i;

    list2.Add(employeeDictionary);

}
IQueryable<EmployeeDictionary> queryable2 = list2.AsQueryable();
IQueryable<EmployeeDictionary> result2 = queryable2.Where("Age==3"); //ParseException raised!
IQueryable<EmployeeDictionary> result2 = queryable2.Where("Value.Age==3"); //ParseException raised!

I guess there must be a way to tell dynamic-linq how the list items should be cast but I'm having an hard time to find how.

UPDATE

I took an Employee class as an example so everyone could understand but the reason why I use a dictionary is because it will be filled from a dataReader generated from a dynamic sql query. The where clause should also be dynamic.

1
0
8/4/2015 8:33:52 PM

Popular Answer

Just don't use dynamic linq at all, since you already have the field information in a dictionary, which doesn't use static lookups of its keys.

IQueryable<EmployeeDictionary> result2 = queryable2
    .Where(dictionary => object.Equals(dictionary["Age"], 3));
0
8/4/2015 8:26:18 PM


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