简体   繁体   中英

best way to build the dynamic linq queries in c#?

I want to know which is the best way to build dynamic queries in LINQ. Queries will be complex and nested. While searching I found a few ways:

  1. Linq dynamic (System.Linq.Dynamic)
  2. Albahari's Predicate builder class
  3. Linq.Expression

There may be more options than these. Which is the best way?

This depends on your circumstances: how fast do you need it, what is your starting point, and so on. In an unconstrained world, I think the best thing is to roll your own library for building dynamic queries. You can use Scott's or Joseph's work as an inspiration, but in the end it all "bottoms out" in the Linq.Expression library.

One advantage to the "do it yourself" approach is that you would not need to bridge from your code to someone's framework. Rather, you would code directly to .NET APIs. This may be useful when you already have a representation of your dynamic queries, for example, in a model that you present to users through a UI, in an XML file, etc. All you need is to walk that representation recursively, and produce System.Linq.Expression as the return.

FWIW, my company took this approach when .NET 3.5 came out, and we are very happy with the outcome.

Linq queries can be written in two ways and let you use any kind of nesting.

Query Syntax

IEnumerable<int> numQuery1 = 
        from num in numbers
        where num % 2 == 0
        orderby num
        select num;

Method Syntax

 IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);

For more information about Linq, you can visit Microsoft's LINQ (Language-Integrated Query) . It contains everything from getting started to sample tutorials

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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