简体   繁体   English

有没有一种方法可以使用System.Linq.Dynamic查询类型

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

I have class "A" which has a collection of class "B". 我有“ A”类,其中有“ B”类的集合。 "D" is a subclass of "B" with the property "DMatter" (not inherited from "B") “ D”是具有属性“ DMatter”的“ B”的子类(不是从“ B”继承的)

I can select "A"s that have a "D" with certain content like this with regular Linq: 我可以使用常规Linq选择具有某些内容的“ D”的“ A”:

 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: 我可以像这样动态地改变B的属性:

 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? 有什么办法吗?

This functionality ( Cast and OfType ) is now implemented in System.Linq.Dynamic.Core . 此功能( CastOfType )现在在System.Linq.Dynamic.Core中实现。

See the api documentation: OfType 请参阅api文档: OfType

Looking through the code of System.Linq.Dynamic.ExpressionParser , it seems that there is no OfType parsing implemented unfortunately. 查看System.Linq.Dynamic.ExpressionParser的代码,似乎不幸的是没有实现OfType解析。 Refer this article about it, where workaround is provided as IQueryable extension methods. 请参阅此文章 ,其中解决方法作为IQueryable扩展方法提供。 It seems it is the most you can get without deep dive into System.Linq.Dynamic.ExpressionParser source. 似乎这是您无需深入研究System.Linq.Dynamic.ExpressionParser源即可获得的最大功能。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM