zoukankan      html  css  js  c++  java
  • 动态linq表达式新方法,Dynamic LINQ Extension Method

    Remember those old posts on Dynamic LINQ? You are probably aware that Microsoft has made its implementation available as a Nuget package, but, like I said, you already have it in your machine, hidden inside the System.Web.Extensions assembly.

    In order to make it easier to use, I wrote a simple extension method that works with plain old IQueryable<T>. And here it is:

       1: public static IQueryable<T> Where<T>(this IQueryable<T> query, String restriction, params Object[] values)
       2: {
       3:     Assembly asm = typeof(UpdatePanel).Assembly;
       4:     Type dynamicExpressionType = asm.GetType("System.Web.Query.Dynamic.DynamicExpression");
       5:     MethodInfo parseLambdaMethod = dynamicExpressionType.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m => (m.Name == "ParseLambda") && (m.GetParameters().Length == 2)).Single().MakeGenericMethod(typeof(T), typeof(Boolean));
       6:     Expression<Func<T, Boolean>> expression = parseLambdaMethod.Invoke(null, new Object[] { restriction, values }) as Expression<Func<T, Boolean>>;
       7:  
       8:     return (query.Where(expression));
       9: }

    It even supports parameters! Just two simple examples – I am using Entity Framework, but you can use whatever you like, this is totally generic:

       1: //without parameters
       2: var productsWithPriceGreaterThan100 = ctx.Products.Where("Price > 100").ToList();
       3:  
       4: //with parameters
       5: var productsWithPriceLowerThan100 = ctx.Products.Where("Price < @0", 100).ToList();

    To make it clear, all parameters must be indicated as @0, @1, and so on. It is better to use them, because the database engine can reuse the execution plan.

    There’s one limitation, though: you can’t compare each value on its own, you have to specify one of its properties. For example, you can’t have:

       1: var productNames = ctx.Products.Select(x => x.Name).Where("@it != @0", "Some Name").ToList();

    The @it parameter is not recognized, which is a pity.

    Make sure you have references to both System.Web and System.Web.Extensions, this is required, and won’t affect anything.

    As always, glad to be of service! Winking smile

  • 相关阅读:
    模拟链表
    解密回文——栈
    解密QQ——队列
    排序算法的实现与比较
    2016年第七届蓝桥杯C/C++B组省赛题目解析
    记账类问题汇总
    斐波那契数列题型汇总
    MFC绘图小实验(1)
    MFC绘图基础——上机操作步骤
    求 pi 的近似值题型汇总
  • 原文地址:https://www.cnblogs.com/handboy/p/3262035.html
Copyright © 2011-2022 走看看