Is there a way to query on Type using System.Linq.Dynamic

c# dynamic-linq linq

Question

I have class "A" which has a collection of class "B". "D" is a subclass of "B" with the property "DMatter" (not inherited from "B")

I can select "A"s that have a "D" with certain content like this with regular Linq:

 var result = 
    Aset.Where(a => a.Bs.OfType<D>().Any(d => d.DMatter.Contains("ii"))); //works!

I can dynamically on B's properties like so:

 var result = Aset.Where("Bs.Any(BStuff.Contains(\"bb\"))");//works!

But I can't find a way to something like this:

result = Aset.Where("Bs.OfType<D>().Any(DMatter.Contains(\"ii\"))");//Explodes!

Any solutions?

1
1
1/13/2014 12:58:27 PM

Accepted Answer

Looking through the code of System.Linq.Dynamic.ExpressionParser, it seems that there is no OfType parsing implemented unfortunately. Refer this article about it, where workaround is provided as IQueryable extension methods. It seems it is the most you can get without deep dive into System.Linq.Dynamic.ExpressionParser source.

public static class MyQueryExtensions
{
    public static IQueryable OfType(this IQueryable source, string typeStr)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }
        if (typeStr == null)
        {
            throw new ArgumentNullException("typeStr");
        }

        Type type = Assembly.GetExecutingAssembly().GetType(typeStr);
        MethodInfo methodOfType = typeof(Queryable).GetMethods().First(m => m.Name == "OfType" && m.IsGenericMethod);

        return source.Provider.CreateQuery(Expression.Call(null, methodOfType.MakeGenericMethod(new Type[] { type }), new Expression[] { source.Expression }));
    }
}

and then you can:

var result = someList.OfType("SomeNamespace.SomeClass");
0
2/5/2014 10:01:22 AM

Popular Answer

This functionality (Cast and OfType) is now implemented in System.Linq.Dynamic.Core.

See the api documentation: OfType



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