How can I run a dynamic LINQ query on a collection of a base type (like the IPerson interface) but access implementation specific properties (like Age).
I can be sure that all items in the collection are the same, i.e. looking at the first type I can assume that the others are the same.
I need this for a UI that can apply filters to di开发者_开发百科fferent collections, the user sees all available properties.
Here's an example of what I'd like to do, the Expression.Call method throws an exception:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Linq.Dynamic;
using DynamicExpression = System.Linq.Dynamic.DynamicExpression;
namespace DynamicLinqTest
{
public interface IPerson
{
string Name { get; set; }
}
public class Person : IPerson
{
public string Name { get; set; }
public int Age { get; set; }
public double Income { get; set; }
}
class Program
{
public static IEnumerable<Person> GetPersons()
{
yield return new Person { Name = "Sam", Age = 26, Income = 50000 };
yield return new Person { Name = "Rick", Age = 27, Income = 0 };
yield return new Person { Name = "Joe", Age = 45, Income = 35000 };
yield return new Person { Name = "Bill", Age = 31, Income = 40000 };
yield return new Person { Name = "Fred", Age = 56, Income = 155000 };
}
static void Main(string[] args)
{
IEnumerable<IPerson> persons = GetPersons();
var personsQueriable = persons.AsQueryable();
//what I would like to do:
// personsQueriable.Where("Age > 30");
var l = DynamicExpression.ParseLambda(persons.First().GetType(), typeof(bool), "Age > 30");
var filtered = personsQueriable.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Where",
new Type[] { persons.First().GetType() },
personsQueriable.Expression, Expression.Quote(l)));
ObjectDumper.Write(filtered);
Console.Read();
}
}
}
You are generating the following code:
persons.Where((Person p) => p.Age > 30)
persons
is of type IEnumerable<IPerson>
, which can't be cast to IEnumerable<Person
>. What you want is to add a call to Queryable.Cast
to cast the IPerson
objects to Person
:
persons.Cast<Person>().Where(p => p.Age > 30)
Use the following code:
var castedQueryable = personsQueriable.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Cast",
new Type[] { persons.First().GetType() },
personsQueriable.Expression));
var l = DynamicExpression.ParseLambda(persons.First().GetType(), typeof(bool), "Age > 30");
var filtered = personsQueriable.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Where",
new Type[] { persons.First().GetType() },
castedQueryable.Expression, Expression.Quote(l)));
However, note that you're in fact enumerating four times persons
here. If it comes from a list, it doesn't have much impact. If the original enumerable comes from a database query, you might want to make sure you're enumerating it only once. Get the results inside a list, then make sure all the First
calls and expressions are applied on it.
精彩评论