第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

擴(kuò)展表達(dá)式

標(biāo)簽:
Java

老外写的一个不错的扩展表达式的文章,原文地址:http://www.albahari.com/nutshell/predicatebuilder.html

Dynamically Composing Expression Predicates

Suppose you wanted to write a LINQ to SQL query that implemented a keyword-style. search. In other words, a query that returned rows whose description contained some or all of a given set of keywords.

We could proceed as follows:

[object Object]IQueryable<Product> SearchProducts (params string[] keywords)
[object Object][object Object]

The temporary variable in the loop is required to avoid the outer variable trap, where the same variable is captured for each iteration of the foreach loop.

So far, so good. But this only handles the case where you want to match all of the specified keywords. Suppose instead, we wanted products whose description contains any of the supplied keywords. Our previous approach of chaining Where operators is completely useless! We could instead chain Union operators, but this would be inefficient. The ideal approach is to dynamically construct a lambda expression tree that performs an or-based predicate.

Of all the things that will drive you to manually constructing expression trees, the need for dynamic predicates is the most common in a typical business application. Fortunately, it’s possible to write a set of simple and reusable extension methods that radically simplify this task. This is the role of our PredicateBuilder class.

Using PredicateBuilder

Here's how to solve the preceding example with PredicateBuilder:

 [object Object]IQueryable<Product> SearchProducts (params string[] keywords)
[object Object][object Object]

PredicateBuilder Source Code

Here's the complete source:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
 
public static class PredicateBuilder
...{
  public static Expression<Func<T, bool>> True<T> ()  ...{ return f => true;  }
  public static Expression<Func<T, bool>> False<T> () ...{ return f => false; }
 
  public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
                                                      Expression<Func<T, bool>> expr2)
  ...{
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.Or (expr1.Body, invokedExpr), expr1.Parameters);
  }

 
  public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                       Expression<Func<T, bool>> expr2)
  ...{
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.And (expr1.Body, invokedExpr), expr1.Parameters);
  }

}

 

PredicateBuilder is also shipped as part of LINQKit, a productivity kit for LINQ to SQL.

How it Works

The True and False methods do nothing special: they are simply convenient shortcuts for creating an Expression<Func<T,bool>> that initially evaluates to true or false. So the following:

var predicate = PredicateBuilder.True <Product> ();

is just a shortcut for this:

Expression<Func<Product, bool>> predicate = c => true;

When you’re building a predicate by repeatedly stacking and/or conditions, it’s useful to have a starting point of either true or false (respectively). Our SearchProducts method still works if no keywords are supplied.

The interesting work takes place inside the And and Or methods. We start by invoking the second expression with the first expression’s parameters. An Invoke expression calls another lambda expression using the given expressions as arguments. We can create the conditional expression from the body of the first expression and the invoked version of the second. The final step is to wrap this in a new lambda expression.

More Examples

A useful pattern in writing a data access layer is to create a reusable predicate library. Your queries, then, consist largely of select and orderby clauses, the filtering logic farmed out to your library. Here's a simple example:

[object Object]public partial class Product
[object Object][object Object]

We can extend this by adding a method that uses PredicateBuilder:

public partial class Product
...{
  public static Expression<Func<Product, bool>> ContainsInDescription (
                                                params string[] keywords)
  ...{
    var predicate = PredicateBuilder.False<Product>();
    foreach (string keyword in keywords)
    ...{
      string temp = keyword;
      predicate = predicate.Or (p => p.Description.Contains (temp));
    }

    return predicate;
  }

}

This offers an excellent balance of simplicity and reusability, as well as separating business logic from expression plumbing logic. To retrieve all products whose description contains “BlackBerry” or “iPhone”, along with the Nokias and Ericssons that are selling, you would do this:

[object Object]var newKids  = Product.ContainsInDescription ("BlackBerry", "iPhone");
[object Object]
[object Object]var classics = Product.ContainsInDescription ("Nokia", "Ericsson")
[object Object]                      .And (Product.IsSelling());
[object Object]var query =
[object Object]  from p in Data.Products.Where (newKids.Or (classics))
[object Object]  select p;

The And and Or methods in boldface resolve to extension methods in PredicateBuilder.
An expression predicate can perform. the equivalent of an SQL subquery by referencing association properties. So, if Product had a child EntitySet called Purchases, we could refine our IsSelling method to return only those products that have sold a minimum number of units as follows:

[object Object]public static Expression<Func<Product, bool>> IsSelling (int minPurchases)
[object Object][object Object]

 

點(diǎn)擊查看更多內(nèi)容
TA 點(diǎn)贊

若覺得本文不錯(cuò),就分享一下吧!

評(píng)論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評(píng)論
  • 收藏
  • 共同學(xué)習(xí),寫下你的評(píng)論
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會(huì)
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)

舉報(bào)

0/150
提交
取消