Home Database Mysql Tutorial Linq技术四:动态Linq技术--Linq.Expressions

Linq技术四:动态Linq技术--Linq.Expressions

Jun 07, 2016 pm 03:56 PM
linq dynamic technology

前面介绍了Linq的三个方面应用:Linq to SQL, Linq to XML和Linq to Object,这篇介绍一下动态Linq的实现方式及应用场景。 命名空间: System.Linq; System.Linq.Expressions; 应用Linq的时候,我们都知道只需要Lambda表达式就行,但有些场景仅仅只使用Data

前面介绍了Linq的三个方面应用:Linq to SQL, Linq to XML和Linq to Object,这篇介绍一下动态Linq的实现方式及应用场景。

命名空间:

System.Linq;

System.Linq.Expressions;

应用Linq的时候,我们都知道只需要Lambda表达式就行,但有些场景仅仅只使用Data Model的字段名操作是不够的或者不方便的。

场景1:假设我们需要拼接Where条件进行查询,一种方式可以拼接IQueryable的表达式。但我想像写SQL语句那样直接拼接一个Where条件就行,Linq要怎么实现?

场景2:假设我们想要一个列表,这个列表可以按每个表头来排序,我们把表头当作参数传给排序函数,在函数内部该怎么实现呢?可以逐一枚举对比,针对不同的列写不同的Linq语句,但代码很冗余。用传统方式根据动态字段名怎么实现?

下面来说说Linq的另一种应用方式: 动态Linq,使用Linq.Expressions. 场景1, 我只想用Where拼接(表名参数)就完成操作,下面看看实现。下面所有的Demo只是应用于Linq to SQL, 如果是Entity Framework会有差异.

DataClasses1DataContext dbContext = new DataClasses1DataContext();

public string dynamicLinq(int id = 50)
{
IQueryable dLinq = dbContext.DataListForDemos;

ParameterExpression paraExpr = Expression.Parameter(typeof(DataListForDemo), "data");
MemberExpression propExpr = Expression.Property(paraExpr, typeof(DataListForDemo).GetProperty("ID"));
BinaryExpression filter = Expression.LessThan(propExpr, Expression.Constant(id));
LambdaExpression lambdaWhere = Expression.Lambda(filter, paraExpr);

MethodCallExpression Where = Expression.Call(typeof(Queryable),
"Where",
new Type[] { typeof(DataListForDemo) },
Expression.Constant(dLinq),
lambdaWhere
);

var data0 = dLinq.AsQueryable().Provider.CreateQuery(Where);


DbCommand comm = dbContext.GetCommand(data0);
dbContext.Log(comm.CommandText);

return comm.CommandText;
}

上面是各种Linq.Expression的类, 用ParameterExpression定义参数也就是要操作的实体对象, 用PropertyExpression定义属性也就是要操作的字段, 用BinaryExpression定义条件查询的表达式也就是Where条件, 用LambdaExpression定义Lambda表达式也就是IQueryable对象, 最后一步就是来完成调用. Call方法是来定义你的表达式方法, 如: Where, Select, OrderBy, GroupBy, All, Any, Equal等等方法, 有哪一种动态需求就写哪一种方法, 这个在MSDN上面没有太多实例, 不过网上可以查到很多.

上面返回的是生成的SQL语句, SQL语句是这样的:

SELECT [t0].[ID], [t0].[col1], [t0].[col2], [t0].[col3], [t0].[col5], [t0].[col4]
FROM [dbo].[DataListForDemo] AS [t0]
WHERE [t0].[ID]

对照生成的SQL语句和Expression的表达式就很容易理解Linq是怎么实现的和怎么工作的. 那么有些人会问, IQueayable和IEnuerable的对象都会带有Linq的表达式而并不是单独的方法通过传参数实现, 要实现这种方式那么就得提一下什么是扩展方法以及扩展方法怎么实现. 在C#里面要扩展某个对象的方法可以override基类方法, 但是像string, iqueryable等这种对象怎么扩展它们的方法呢? Override基类当然不行, 这时就要用this关键字,也是this的另一种应用方式.

使用扩展方法, 首先写一个静态类, 在静态类里面定义一个静态方法, 静态方法里面第一个参数以this开始, 第一个参数也就是你要扩展的系统对象.

如:

public static class DynamicQueryable

{

//扩展IQueryable对象的方法

public static IQueryable Where(this IQueryable source, string predicate, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (predicate == null) throw new ArgumentNullException("predicate");
LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Where",
new Type[] { source.ElementType },
source.Expression, Expression.Quote(lambda)));
}

public static LambdaExpression ParseLambda(Type itType, Type resultType, string expression, params object[] values)
{
return ParseLambda(new ParameterExpression[] { Expression.Parameter(itType, "") }, resultType, expression, values);
}

}

上面就是扩展IQueryabler方法, 所以IQueryable类型的所有对象都有了动态Where的功能, 我不知道为什么Microsoft团队没有把这个功能加上, 而只是提供了Expressions类, 加上这些动态表达之后Linq功能会非常强壮.

来看看调用:

public string SelectDynamic(int id = 0)
{
DataListForDemo model = dbContext.DataListForDemos.Where("ID = " + id.ToString()).SingleOrDefault();
return model.ID.ToString();
}

现在很明显的一个变化是Where里面可以只写一个拼接的where条件了, 而且是一个字符串, 这就是大多数程序员想到的东东吧!

Linq里面所有已经存在的方法都可以通过这种方式扩展和实现动态化, 更多的实现方式可以Google, 建议使用Google, 英文文章有的写得非常透彻,而且资源丰富.

 
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Convert VirtualBox fixed disk to dynamic disk and vice versa Convert VirtualBox fixed disk to dynamic disk and vice versa Mar 25, 2024 am 09:36 AM

When creating a virtual machine, you will be asked to select a disk type, you can select fixed disk or dynamic disk. What if you choose fixed disks and later realize you need dynamic disks, or vice versa? Good! You can convert one to the other. In this post, we will see how to convert VirtualBox fixed disk to dynamic disk and vice versa. A dynamic disk is a virtual hard disk that initially has a small size and grows in size as you store data in the virtual machine. Dynamic disks are very efficient at saving storage space because they only take up as much host storage space as needed. However, as disk capacity expands, your computer's performance may be slightly affected. Fixed disks and dynamic disks are commonly used in virtual machines

This article is enough for you to read about autonomous driving and trajectory prediction! This article is enough for you to read about autonomous driving and trajectory prediction! Feb 28, 2024 pm 07:20 PM

Trajectory prediction plays an important role in autonomous driving. Autonomous driving trajectory prediction refers to predicting the future driving trajectory of the vehicle by analyzing various data during the vehicle's driving process. As the core module of autonomous driving, the quality of trajectory prediction is crucial to downstream planning control. The trajectory prediction task has a rich technology stack and requires familiarity with autonomous driving dynamic/static perception, high-precision maps, lane lines, neural network architecture (CNN&GNN&Transformer) skills, etc. It is very difficult to get started! Many fans hope to get started with trajectory prediction as soon as possible and avoid pitfalls. Today I will take stock of some common problems and introductory learning methods for trajectory prediction! Introductory related knowledge 1. Are the preview papers in order? A: Look at the survey first, p

The Stable Diffusion 3 paper is finally released, and the architectural details are revealed. Will it help to reproduce Sora? The Stable Diffusion 3 paper is finally released, and the architectural details are revealed. Will it help to reproduce Sora? Mar 06, 2024 pm 05:34 PM

StableDiffusion3’s paper is finally here! This model was released two weeks ago and uses the same DiT (DiffusionTransformer) architecture as Sora. It caused quite a stir once it was released. Compared with the previous version, the quality of the images generated by StableDiffusion3 has been significantly improved. It now supports multi-theme prompts, and the text writing effect has also been improved, and garbled characters no longer appear. StabilityAI pointed out that StableDiffusion3 is a series of models with parameter sizes ranging from 800M to 8B. This parameter range means that the model can be run directly on many portable devices, significantly reducing the use of AI

DualBEV: significantly surpassing BEVFormer and BEVDet4D, open the book! DualBEV: significantly surpassing BEVFormer and BEVDet4D, open the book! Mar 21, 2024 pm 05:21 PM

This paper explores the problem of accurately detecting objects from different viewing angles (such as perspective and bird's-eye view) in autonomous driving, especially how to effectively transform features from perspective (PV) to bird's-eye view (BEV) space. Transformation is implemented via the Visual Transformation (VT) module. Existing methods are broadly divided into two strategies: 2D to 3D and 3D to 2D conversion. 2D-to-3D methods improve dense 2D features by predicting depth probabilities, but the inherent uncertainty of depth predictions, especially in distant regions, may introduce inaccuracies. While 3D to 2D methods usually use 3D queries to sample 2D features and learn the attention weights of the correspondence between 3D and 2D features through a Transformer, which increases the computational and deployment time.

'Minecraft' turns into an AI town, and NPC residents role-play like real people 'Minecraft' turns into an AI town, and NPC residents role-play like real people Jan 02, 2024 pm 06:25 PM

Please note that this square man is frowning, thinking about the identities of the "uninvited guests" in front of him. It turned out that she was in a dangerous situation, and once she realized this, she quickly began a mental search to find a strategy to solve the problem. Ultimately, she decided to flee the scene and then seek help as quickly as possible and take immediate action. At the same time, the person on the opposite side was thinking the same thing as her... There was such a scene in "Minecraft" where all the characters were controlled by artificial intelligence. Each of them has a unique identity setting. For example, the girl mentioned before is a 17-year-old but smart and brave courier. They have the ability to remember and think, and live like humans in this small town set in Minecraft. What drives them is a brand new,

More than just 3D Gaussian! Latest overview of state-of-the-art 3D reconstruction techniques More than just 3D Gaussian! Latest overview of state-of-the-art 3D reconstruction techniques Jun 02, 2024 pm 06:57 PM

Written above & The author’s personal understanding is that image-based 3D reconstruction is a challenging task that involves inferring the 3D shape of an object or scene from a set of input images. Learning-based methods have attracted attention for their ability to directly estimate 3D shapes. This review paper focuses on state-of-the-art 3D reconstruction techniques, including generating novel, unseen views. An overview of recent developments in Gaussian splash methods is provided, including input types, model structures, output representations, and training strategies. Unresolved challenges and future directions are also discussed. Given the rapid progress in this field and the numerous opportunities to enhance 3D reconstruction methods, a thorough examination of the algorithm seems crucial. Therefore, this study provides a comprehensive overview of recent advances in Gaussian scattering. (Swipe your thumb up

Python underlying technology revealed: how to implement hash algorithm Python underlying technology revealed: how to implement hash algorithm Nov 08, 2023 pm 06:40 PM

Revealing the underlying technology of Python: How to implement the hash algorithm, specific code examples are required Summary: The hash algorithm is one of the commonly used technologies in the computer field and is used to quickly determine the unique identification of data. As a high-level language, Python provides many built-in hash functions, such as the hash() function and the implementation of various hash algorithms. This article will reveal the principles of hashing algorithms and the details of Python's underlying implementation, and provide specific code examples. Introduction to Hash Algorithm Hash algorithm, also known as hash algorithm, is a method of converting data of any length into

Review! Deep model fusion (LLM/basic model/federated learning/fine-tuning, etc.) Review! Deep model fusion (LLM/basic model/federated learning/fine-tuning, etc.) Apr 18, 2024 pm 09:43 PM

In September 23, the paper "DeepModelFusion:ASurvey" was published by the National University of Defense Technology, JD.com and Beijing Institute of Technology. Deep model fusion/merging is an emerging technology that combines the parameters or predictions of multiple deep learning models into a single model. It combines the capabilities of different models to compensate for the biases and errors of individual models for better performance. Deep model fusion on large-scale deep learning models (such as LLM and basic models) faces some challenges, including high computational cost, high-dimensional parameter space, interference between different heterogeneous models, etc. This article divides existing deep model fusion methods into four categories: (1) "Pattern connection", which connects solutions in the weight space through a loss-reducing path to obtain a better initial model fusion

See all articles