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?

Était-ce utile?

La solution 2

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");

Autres conseils

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

See the api documentation: OfType

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top