Dynamic Linq query on a base type collection to retrieve type-specific characteristics

c# dynamic-linq linq

Question

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 different 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();
        }
    }
}
1
1
8/8/2011 5:20:41 PM

Accepted Answer

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.

2
8/8/2011 8:00:40 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