Is there a pattern using Linq to dynamically create a filter?

后端 未结 4 778
忘了有多久
忘了有多久 2020-11-27 06:07

Is there a pattern using Linq to dynamically create a filter?

I have the need to create custom filtering on a list, in the past I would just dynamically create the S

4条回答
  •  借酒劲吻你
    2020-11-27 06:57

    Check out the Dynamic Linq Library from ScottGu's blog:

    For example, below is a standard type-safe LINQ to SQL VB query that retrieves data from a Northwind database and displays it in a ASP.NET GridView control:

    Dim Northwind As New NorthwindDataContext
    Dim query = From q In Northwind.Products Where p.CategoryID = 2 And p.UnitPrice > 3 Order By p.SupplierID Select p
    
    Gridview1.DataSource = query
    GridView1.DataBind()
    

    Using the LINQ DynamicQuery library I could re-write the above query expression instead like so

    Dim Northwind As New NorthwindDataContext
    Dim query = Northwind.Products .where("CategoryID=2 And UnitPrice>3") . OrderBy("SupplierId")
    Gridview1.DataSource = query
    GridView1.DataBind()
    

    Notice how the conditional-where clause and sort-orderby clause now take string expressions instead of code expressions. Because they are late-bound strings I can dynamically construct them. For example: I could provide UI to an end-user business analyst using my application that enables them to construct queries on their own (including arbitrary conditional clauses).

提交回复
热议问题