简体   繁体   English

在c#中构建动态linq查询的最佳方法?

[英]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. 我想知道在LINQ中构建动态查询的最佳方法是哪种。 Queries will be complex and nested. 查询将是复杂和嵌套的。 While searching I found a few ways: 在搜索时我找到了几种方法:

  1. Linq dynamic (System.Linq.Dynamic) Linq动态(System.Linq.Dynamic)
  2. Albahari's Predicate builder class Albahari的Predicate建设者课程
  3. Linq.Expression 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. 您可以使用Scott或Joseph的作品作为灵感,但最终它在Linq.Expression库中“全部结束”。

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. 相反,您可以直接编写.NET API代码。 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. 当您已经拥有动态查询的表示时,这可能很有用,例如,在通过UI,XML文件等呈现给用户的模型中。您只需要递归地遍历该表示,并生成系统.Linq.Expression作为回归。

FWIW, my company took this approach when .NET 3.5 came out, and we are very happy with the outcome. FWIW,我的公司在.NET 3.5发布时采用了这种方法,我们对结果非常满意。

Linq queries can be written in two ways and let you use any kind of nesting. Linq查询可以用两种方式编写,让您使用任何类型的嵌套。

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) . 有关Linq的更多信息,您可以访问Microsoft的LINQ(语言集成查询) It contains everything from getting started to sample tutorials 它包含从入门到示例教程的所有内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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