LINQ – LINQKit(PredicateBuilder)

LINQ – LINQKit(PredicateBuilder)

之前我們在用LINQ的OR條件的時候,都是先確定了查詢的參數有幾個,例如:

string b = "b";
var list = Dinners.Where(p=>p.Title == a || p.Title == b);
list.Dump();

因為不同的Where串聯起來會變成and,所以在查詢參數個數不確定的時候,沒辦法直接使用。

這時候可以利用LINQKit裡面提供的PredicateBuilder類別,就可以輕鬆的建立or查詢條件。

{
  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }
  return dataContext.Products.Where (predicate);
}

除此之外,LINQKit還提供了其它好用的方法,摘錄自LINQKit網站:

LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users. It comprises the following:

With LINQKit, you can:

  • Plug expressions into EntitySets and EntityCollections
  • Use expression variables in subqueries
  • Combine expressions (have one expression call another)
  • Dynamically build predicates
  • Leverage AsExpandable to add your own extensions.

AsExpandable is based on a very clever project by Tomas Petricek. ExpressionVisitor comes from a sample by Matt Warren.

LINQKit includes full source code, and is released under a permissive free license.

image

其它的就留給大家自行研究啦!

 

相關連結:

LINQKit

DotBlogs 的標籤: