LINQ教程
- 格式:docx
- 大小:102.94 KB
- 文档页数:24
LINQ教程之LINQ操作语法LINQ查询时有两种语法可供选择:查询表达式语法(Query Expression)和⽅法语法(Fluent Syntax)。
⼀、查询表达式语法查询表达式语法是⼀种更接近SQL语法的查询⽅式。
LINQ查询表达式语法如下:from<range variable> in <IEnumerable<T> or IQueryable<T> Collection><Standard Query Operators> <lambda expression><select or groupBy operator> <result formation>LINQ查询表达式约束LINQ查询表达式必须以from⼦句开头,以select或group⼦句介绍关键字功能from....in...指定要查询的数据源以及范围变量,多个from⼦句则表⽰从多个数据源查找数据。
注意:C#编译器会把“复合from⼦句”的查询表达式转换为SelectMany()扩展⽅法。
join…in…on…equals…指定多个数据源的关联⽅式let引⼊⽤于存储查询表达式中⼦表达式结果的范围变量。
通常能达到层次感会更好,使代码更易于阅读。
orderby、descending 指定元素的排序字段和排序⽅式。
当有多个排序字段时,由字段顺序确定主次关系,可指定升序和降序两种排序⽅式where指定元素的筛选条件。
多个where⼦句则表⽰了并列条件,必须全部都满⾜才能⼊选。
每个where⼦句可以使⽤谓词&&、||连接多个条件表达式。
group指定元素的分组字段。
select指定查询要返回的⽬标数据,可以指定任何类型,甚⾄是匿名类型。
(⽬前通常被指定为匿名类型)into 提供⼀个临时的标识符。
该标识可以引⽤join、group和select⼦句的结果。
跟我学LINQ TO SQL●LINQ是Language Integrated Query的简称,它是集成在.NET编程语言中的一种特性。
已成为编程语言的一个组成部分,在编写程序时可以得到很好的编译时语法检查,丰富的元数据,智能感知、静态类型等强类型语言的好处。
并且它同时还使得查询可以方便地对内存中的信息进行查询而不仅仅只是外部数据源。
●LINQ定义了一组标准查询操作符用于在所有基于.NET平台的编程语言中更加直接地声明跨越、过滤和投射操作的统一方式,标准查询操作符允许查询作用于所有基于IEnumerable<T>接口的源,并且它还允许适合于目标域或技术的第三方特定域操作符来扩大标准查询操作符集,更重要的是,第三方操作符可以用它们自己的提供附加服务的实现来自由地替换标准查询操作符,根据LINQ模式的习俗,这些查询喜欢采用与标准查询操作符相同的语言集成和工具支持。
●LINQ架构●相关命名空间一.LINQ简介●LINQ包括五个部分:LINQ to Objects、LINQ to DataSets、LINQ to SQL、LINQ toEntities、LINQ to XML。
●LINQ to SQL全称基于关系数据的.NET语言集成查询,用于以对象形式管理关系数据,并提供了丰富的查询功能。
其建立于公共语言类型系统中的基于SQL的模式定义的集成之上,当保持关系型模型表达能力和对底层存储的直接查询评测的性能时,这个集成在关系型数据之上提供强类型。
●LINQ to XML在System.Xml.LINQ命名空间下实现对XML的操作。
采用高效、易用、内存中的XML工具在宿主编程语言中提供XPath/XQuery功能等。
●第一步:建立dbml(Database Mark Language.数据库描述语言,是一种XML格式的文档,用来描述数据库,有点类似Nhibernate的映射文件)●第二步:创建一个页面,页面加入一个GridView控件●第三步:编写代码进行数据绑定●第四步:执行代码public partial class _Default : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){BindData();}}public void BindData(){NorthwindDataContext nt = new NorthwindDataContext();GridView1.DataSource = from c in nt.Customers select c.Orders;GridView1.DataBind();}}●LINQ是在之上的,那么在将来它会代替吗?●在大型项目中使用LINQ,它的效率如何呢?二.DataContenxt一、作用DataContext类型(数据上下文)是System.Data.Linq命名空间下的重要类型,用于把查询句法翻译成SQL语句,以及把数据从数据库返回给调用方和把实体的修改写入数据库。
Linq基础1.1 LINQ简介LINQ(Language Integrated Query)是C#3.0语言新增的一个扩展,可以处理非常大的对象集合,这一般需要选择集合的一个子集来完成执行程序的任务。
Linq提供了很多扩展方法便于集合的排序、组合和计算查询结果的统计数据。
VS2008带有3个内置的LIN Q变体:Linq to Objects Linq to SQL Linq to XML,它们为不同的数据提供了查询方案:Linq to Objects:为任意类型的C#内存对象提供查询,如数组、列表和其它集合类型。
Linq to SQL:为使用标准SQL数据库查询语言的关系数据库提供查询,如SQL Se rver、Oracle等数据库。
Linq to XML:提供XML文档的创建和处理功能。
1.2 第一LINQ查询下面我们使用Linq实现一个对数组的查找功能,代码如下:示例1class Program{static void Main(string[] args){string[] names = { "alonso", "zheng", "smith", "jon es", "smythe", "small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "singh" };var result = from n in names where n.StartsWith("s") select n;Console.WriteLine("以s开头的名字为:");foreach (var item in result){Console.WriteLine(item);}}}示例说明:命名空间:System.Linq;用var关键字声明结果变量;var声明的变量不用指定类型,编译器会自动根据结果推断出该类型。
LINQ中文教程一、LINQ概述LINQ是一种查询技术,它允许开发人员使用统一语法进行查询,无论是对于集合、数据库、XML还是其他数据源。
它支持对数据源进行过滤、排序、分组和投影等操作。
LINQ主要有以下几个方面的特点:1.统一的查询语法:LINQ提供了一种统一的查询语法,无论是对于集合还是其他数据源,开发人员都可以使用相同的语法进行查询。
2.编译时类型检查:LINQ的查询表达式是在编译时进行类型检查的,这样可以在编译时就发现错误,提高了代码的健壮性。
3.延迟加载:LINQ的查询通常支持延迟加载,只有在需要结果时才会执行查询操作,这样可以提高性能和效率。
4.集成查询:通过LINQ,可以对多个数据源进行集成查询,无论是集合、数据库还是XML等,都可以使用相同的查询语法进行查询和操作。
5.可组合性:LINQ的查询操作可以进行组合,可以将多个查询操作串联起来,形成复杂的查询链。
二、LINQ的用法1.查询语法LINQ提供了一种类似于SQL的查询语法,通过关键字from、where、select等来描述查询过程。
例如,对于一个整数集合,可以使用如下的查询语法来查询大于10的数字:```var query = from num in numberswhere num > 10select num;```其中,numbers是一个整数集合,num是每个元素的别名,select num表示选择满足条件的元素。
2.方法语法除了查询语法,LINQ还提供了一种方法语法,通过调用特定的查询方法来实现查询。
例如,对于上述的查询,可以使用方法语法来实现:```var query = numbers.Where(num => num > 10);```其中,Where是一个查询方法,num => num > 10表示一个Lambda表达式,表示筛选大于10的数字。
3.查询结果的使用通过LINQ的查询语法或方法语法,可以得到一个查询结果,可以将其转换为各种类型,进行进一步的操作。
目前本人收集的最全的LINQ入门资料大家一起LINQ吧入门教程系列1LinqtoSql(一):DataConte某t与实体LinqtoSql(二):增删改LinqtoSql(三):查询句法LinqtoSql(四):存储过程LinqtoSql(五):探究特性LinqtoSql(六):并发与事务LinqtoSql(七):继承与关系Linqtoql(八):其它入门教程系列2LINQ体验(1)——ViualStudio2022新特性我平时利用课余零碎时间来学习3.5、LINQ、Silverlight、3.5E某tenion等新东西,通过笔记形式来记录自己所学的历程,也给大家一起学习ViualStudio2022和.NET3.5提供一个平台,为保证此系列的完整性,我打算先依次介绍一下C#3.0新语言特性和改进,然后从一条一条LINQ语句分析来贯穿LINQ的知识点……LINQ体验(2)——C#3.0新语言特性和改进(上篇)LINQ体验(3)——C#3.0新语言特性和改进(下篇)LINQ体验(4)——LINQ简介和LINQtoSQL语句之WhereLINQ是LanguageIntegratedQuery的简称,它是集成在.NET编程语言中的一种特性。
已成为编程语言的一个组成部分,在编写程序时可以得到很好的编译时语法检查,丰富的元数据,智能感知、静态类型等强类型语言的好处。
并且它同时还使得查询可以方便地对内存中的信息进行查询而不仅仅只是外部数据源。
…LINQ体验(5)——LINQtoSQL语句之Select/Ditinct和Count/Sum/Min/Ma某/AvgLINQ体验(6)——LINQtoSQL语句之Join和OrderByLINQ体验(7)——LINQtoSQL语句之GroupBy/Having和E某it/In/Any/All/Contain我们继续讲解LINQtoSQL语句,这篇我们来讨论GroupBy/Having操作符和E某it/In/Any/All/Contain操作符。
linq或用法-回复如何使用LINQ(语言集成查询)进行数据查询和操作。
LINQ(Language Integrated Query)是.NET框架中的一个功能强大的查询工具,它允许开发人员使用统一的语法查询和操作各种数据源,如对象、集合、数据库和XML等。
本文将详细介绍LINQ的使用方法,包括查询操作符、延迟求值、数据排序和过滤等。
第一步:创建LINQ查询在开始使用LINQ之前,首先需要明确你要查询的数据源是什么。
这可以是一个对象集合、数据库表、XML文件等等。
假设我们要从一个对象集合中查询数据,首先需要创建一个表示该集合的对象。
csharpList<int> Numbers = new List<int> { 1, 2, 3, 4, 5, 6 };在上面的代码中,我们创建了一个名为Numbers的整数列表,其中包含了从1到6的数字。
第二步:使用查询操作符一旦我们创建了数据源,就可以使用查询操作符来对数据进行查询和操作。
常见的查询操作符包括Where、Select、OrderBy等。
下面将介绍一些常用的查询操作符。
1. Where:用于根据指定的条件筛选数据。
例如,我们可以使用Where 操作符来筛选出大于3的数字。
csharpvar result = Numbers.Where(n => n > 3);在上面的代码中,我们使用Where操作符和Lambda表达式来筛选出大于3的数字,结果将存储在result变量中。
2. Select:用于选择指定的数据。
例如,我们可以使用Select操作符来选择数字的平方。
csharpvar result = Numbers.Select(n => n * n);在上面的代码中,我们使用Select操作符和Lambda表达式来选择数字的平方,结果将存储在result变量中。
3. OrderBy:用于按照指定的属性对数据进行排序。
linq常用语法和方法LINQ(Language Integrated Query)是一种强大的查询语言,用于在.NET框架中查询各种数据源。
它提供了许多常用的语法和方法,用于对数据进行筛选、排序、聚合等操作。
以下是一些LINQ常用的语法和方法:1. 查询语法(Query Syntax):通过使用标准的LINQ查询运算符(如`from`、`where`、`select`、`orderby`等),可以编写结构化查询语句。
例如:```csharpvar query = from item in collectionwhere == valueselect item;```2. 扩展方法语法(Extension Methods Syntax):通过使用LINQ扩展方法,可以使用Lambda表达式和委托来编写查询。
这些扩展方法提供了简洁的语法,以便对各种数据源进行操作。
例如:```csharpvar query = (item => == value);```3. 聚合操作:LINQ提供了许多聚合操作符,如`Count()`、`Sum()`、`Average()`等,可以对查询结果进行统计和计算。
例如:```csharpvar count = ();var sum = (item => );```4. 排序操作:使用`OrderBy()`和`OrderByDescending()`方法可以对查询结果进行排序。
还可以使用`ThenBy()`方法进行多级排序。
例如:```csharpvar sorted = (item => );```5. 转换操作:使用`Select()`方法可以对查询结果进行转换,将每个元素转换为指定的类型或表达式。
例如:```csharpvar transformed = (item => + " converted");```6. 分组操作:使用`GroupBy()`方法可以对查询结果进行分组,并根据指定的键对每个组进行聚合。
c#之linq——⼩⽩⼊门级通过本⽂需要掌握的关于linq的知识点为:linq的基本概念及其特点linq中常见操作及使⽤linq常见的⽅法查询1 Linq基本概念1.1 ling定义Linq(Language Integrated Query),语⾔集成查询,是⼀种使⽤类似SQL语句操作多种数据源的功能。
如,我们可以使⽤c#查询access数据库、.net数据集、xml⽂档以及实现了IEnumerable或IEnumerable<T>接⼝的集合类(如List,Array,SortedSet,Stack,Queue等,可以进⾏遍历的数据结构都会集成该类)。
从.net framework3.5中开始引⼊,能够提升程序数据处理能⼒和开发效率,具有集成性、统⼀性、可扩展性、抽象性、说明式编程、可组成型、可转换性等优势。
1.2 linq提供的程序Linq to Object。
提供程序查询内存中的集合和数组。
Linq to DataSet。
提供程序查询数据集中的数据。
Linq to SQL。
提供程序查询和修改Sql Server数据库中的数据,将应⽤程序中的对象模型映射到数据库表。
Linq to Entities。
使⽤linq to entities时,会在后台将linq语句转换为sql语句与数据库交互,并能提供数据变化追踪。
Linq to XML。
提供程序查询和修改XML,既能修改内存中的xml,也可以修改从⽂件中加载的。
2 Linq查询linq查询包括两种⽅式,⼀是语句查询,⼆是⽅法查询。
语句查询使⽤较多,也更容易理解,微软官⽹推荐使⽤。
下⾯介绍语句查询的⼦句使⽤。
2.1 from⼦句⽤来标识查询的数据源。
基本语法格式为:from 迭代变量 in 数据源⾸先,通过以下简单⽰例,给出from⽤法static void Main(string[] args){var nums = new int[] {56,97,98,57,74,86,31,90};var queryInfo = from num in nums select num;//num为数据中的每个元素(相当于foreach中迭代变量)var numStr = string.Empty;foreach (var item in queryInfo){numStr += item + " ";}Console.WriteLine($"数据元素包括:{numStr}");}运⾏结果如下图:注:查询表达式在循环访问查询变量时(如上述⽰例中foreach),才会执⾏。
LINQ教程范文在LINQ中,查询是通过查询表达式或方法来进行的。
查询表达式是一种声明性的语法形式,类似于SQL。
它使用一些关键字(如from、where、select等)来描述查询的逻辑。
下面是一个使用查询表达式的示例:```csharpvar result = from student in studentswhere student.Age > 18select ;```上面的代码表示从一个名为"students"的集合中,选取年龄大于18岁的学生的姓名。
通过查询表达式,我们可以很清晰地描述出我们需要的数据,而不用过多关注查询的具体实现。
另一种进行LINQ查询的方式是使用LINQ方法。
LINQ方法是一组特定于数据类型的扩展方法,可以用于对数据集合进行筛选、排序、投影等操作。
下面是一个使用LINQ方法的示例:```csharpvar result = students.Where(student => student.Age > 18).Select(student => );```上面的代码与前面的查询表达式示例实现的功能是相同的。
通过链式调用LINQ方法,我们可以很方便地对数据进行管道式的操作,而无需写复杂的循环和条件判断。
除了上面介绍的基本查询,LINQ还提供了许多其他的功能和特性。
比如可以对查询结果进行分组、连接多个数据集合、进行聚合操作等。
此外,LINQ还支持对数据库进行查询。
通过LINQ to SQL或Entity Framework等技术,我们可以直接在代码中通过LINQ查询数据库,而无需编写复杂的SQL语句。
1、LINQ表达式LINQ语言集成查询(Language Integrated Query)LINQ 最明显的“语言集成”部分是查询表达式。
查询表达式是使用C# 3.0 中引入的声明性查询语法编写的。
通过使用查询语法,您甚至可以使用最少的代码对数据源执行复杂的筛选、排序和分组操作。
您使用相同的基本查询表达式模式来查询和转换SQL 数据库、 数据集、XML 文档和流以及 .NET 集合中的数据。
下面的示例演示了完整的查询操作。
完整操作包括创建数据源、定义查询表达式,以及在foreach语句中执行查询。
class LINQQueryExpressions{static void Main(){// Specify the data source.int[] scores = new int[] { 97, 92, 81, 60, 89, 45, 34, 78 };// Define the query expression.IEnumerable<int> scoreQuery =from score in scoreswhere score > 80select score;// Execute the query.foreach (int i in scoreQuery){Console.Write(i + " ");}}}// Output: 97 92 81 892、LINQ查询“查询”是指一组指令,这些指令描述要从一个或多个给定数据源检索的数据以及返回的数据应该使用的格式和组织形式。
查询不同于它所产生的结果。
通常,源数据会在逻辑上组织为相同种类的元素序列。
SQL 数据库表包含一个行序列。
与此类似, DataTable 包含一个DataRow 对象序列。
在XML 文件中,有一个XML 元素“序列”(不过这些元素按分层形式组织为树结构)。
内存中的集合包含一个对象序列。
LINQ TO SQL 学习笔记1. 预备知识 (3)1.1.Linq介绍 (3)1.2.隐含类型局部变量 (3)1.3.匿名类型 (4)1.4.扩展方法 (5)1.5.自动属性 (6)1.6.对象初始化器/集合初始化器 (6)mbda表达式与Lambda表达树 (7)1.8.查询句法 (9)2. DataContent与实体 (10)2.1.DataContent (10)2.2.实体类 (10)2.3.强类型DataContent (11)2.4.日志功能 (11)2.5.探究查询 (12)2.6.执行查询 (13)2.7.创建数据库 (13)2.8.使用DbDataReader数据源 (14)2.9.生成实体类 (14)3. 增删改 (15)3.1.插入(Insert) (15)3.2.更新(Update) (18)3.3.删除(Delete) (18)3.4.使用Attach更新(Update with Attach) (19)3.5.使用Attach更新和删除(Update and Delete with Attach) (21)4. 查询句法 (22)4.1.Select (22)4.2.Where (23)4.3.OrderBy (23)4.4.分页 (24)4.5.分组 (24)4.6.Distinct (25)4.7.Union (25)4.8.Contact (25)4.9.取相交项 (26)4.10.排除相交项 (26)4.11.子查询 (27)4.12.In操作 (27)4.13.Join (28)5. 存储过程 (28)5.1.普通存储过程 (28)5.2.带参数存储过程 (30)5.3.带返回值的存储过程 (30)5.4.多结果集存储过程 (30)5.5.使用存储过程新增/更新/删除数据 (31)6. 探究特性 (33)6.1.延迟执行 (33)6.2.DataLoadOptions (33)6.3.DataLoadOptions限制 (34)6.4.主键缓存 (35)6.5.DataContent隔离 (35)7. 并发与事务 (35)7.1.检测并发 (35)7.2.解决并发 (36)7.3.事务处理 (38)8. 其他 (40)Linq学习笔记(1.6)——ToArray、ToList、ToDictionary、OfType (40)1.预备知识1.1.Linq介绍LINQ是Language Integrated Query的简称,它是集成在.NET编程语言中的一种特性。
About the T utorialThe acronym LINQ stands for Language Integrated Query. Microsoft’s query language is fully integrated and offers easy data access from in-memory objects, databases, XML documents, and many more. It is through a set of extensions LINQ ably integrates queries in C# and Visual Basic.This tutorial offers a complete insight into LINQ with ample examples and coding. The entire tutorial is divided into various topics with subtopics that a beginner can be able to move gradually to more complex topics of LINQ.AudienceThe aim of this tutorial is to offer an easy understanding of LINQ to the beginners who are keen to learn the same.PrerequisitesIt is essential before proceeding to have some basic knowledge of C# and Visual Basic in .NET.Copyright & Disclaimer© Copyright 2018 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute, or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness, or completeness of our website or its contents including this tutorial. If you discover any errors on our website or inthistutorial,******************************************iT able of ContentsAbout the Tutorial (i)Audience (i)Prerequisites (i)Copyright & Disclaimer (i)Table of Contents .................................................................................................................................... i i 1.LINQ ─ OVERVIEW (1)Example of a LINQ query (1)Syntax of LINQ (2)Types of LINQ (3)LINQ Architecture in .NET (3)Query Expressions (4)Extension Methods (5)Difference between LINQ and Stored Procedure (5)Need for LINQ (5)Advantages of LINQ (6)2.LINQ ─ ENVIRONMENT (7)Getting Visual Studio 2010 Installed on Windows 7 (7)Writing C# Program using LINQ in Visual Studio 2010 (11)Writing VB Program using LINQ in Visual Studio 2010 (13)3.LINQ ─ QUERY OPERATORS (15)Filtering Operators (15)Filtering Operators in LINQ (16)Join Operators (17)Join Operators in LINQ (17)Projection Operations (21)Projection Operations in LINQ (21)Sorting Operators (25)Grouping Operators (28)Conversions (30)Concatenation (33)Aggregation (36)Quantifier Operations (38)Partition Operators (41)Generation Operations (45)Set Operations (50)Equality (56)Element Operators (58)4.LINQ ─ SQL (63)Introduction of LINQ To SQL (63)How to Use LINQ to SQL? (64)Querying with LINQ to SQL (66)Insert, Update, and Delete using LINQ to SQL (66)5.LINQ ─ OBJECTS (74)Introduction of LINQ to Objects (74)Querying in Memory Collections Using LINQ to Objects (75)6.LINQ ─ DATASET (78)Introduction of LINQ to Dataset (78)Querying Dataset using LinQ to Dataset (81)7.LINQ ─ XML (85)Introduction of LINQ to XML (85)Read an XML File using LINQ (86)Add New Node (88)Deleting Particular Node (90)8.LINQ ─ ENTITIES (93)LINQ to Entities Query Creation and Execution Process (93)Example of ADD, UPDATE, and DELETE using LINQ with Entity Model (94)9.LINQ ─ LAMBDA EXPRES SIONS (99)Expression Lambda (100)Async Lambdas (100)Lambda in Standard Query Operators (100)Type Inference in Lambda (102)Variable Scope in Lambda Expression (102)Expression Tree (104)Statement Lambda (104)10.LINQ ─ (106)LINQDataSource Control (107)INSERT, UPDATE, and DELETE data in Page using LINQ (110)LINQ 1.Developers across the world have always encountered problems in querying data because of the lack of a defined path and need to master a multiple of technologies like SQL, Web Services, XQuery, etc.Introduced in Visual Studio 2008 and designed by Anders Hejlsberg, LINQ (Language Integrated Query) allows writing queries even without the knowledge of query languages like SQL, XML etc. LINQ queries can be written for diverse data types.Example of a LINQ queryC#using System;using System.Linq;class Program{static void Main(){string[] words = {"hello", "wonderful", "LINQ", "beautiful", "world"};//Get only short wordsvar shortWords = from word in words where word.Length <= 5 select word;//Print each word outforeach (var word in shortWords){Console.WriteLine(word);}Console.ReadLine();}}VBModule Module1Sub Main()Dim words As String() = {"hello", "wonderful", "LINQ", "beautiful", "world"}' Get only short wordsDim shortWords = From word In words _ Where word.Length <= 5 _ Select word' Print each word out.For Each word In shortWordsConsole.WriteLine(word)NextConsole.ReadLine()End SubEnd ModuleWhen the above code of C# or VB is compiled and executed, it produces the following result:helloLINQworldSyntax of LINQThere are two syntaxes of LINQ. These are the following ones.Lamda (Method) Syntaxvar longWords = words.Where( w => w.length > 10);Dim longWords = words.Where(Function(w) w.length > 10)Query (Comprehension) Syntaxvar longwords = from w in words where w.length > 10;Dim longwords = from w in words where w.length > 10T ypes of LINQThe types of LINQ are mentioned below in brief.∙LINQ to Objects∙LINQ to XML(XLINQ)∙LINQ to DataSet∙LINQ to SQL (DLINQ)∙LINQ to EntitiesApart from the above, there is also a LINQ type named PLINQ which is Microsoft’s parallel LINQ.LINQ Architecture in .NETLINQ has a 3-layered architecture in which the uppermost layer consists of the language extensions and the bottom layer consists of data sources that are typically objects implementing IEnumerable <T> or IQueryable <T> generic interfaces. The architecture is shown below.Query ExpressionsQuery expression is nothing but a LINQ query, expressed in a form similar to that of SQL with query operators like Select, Where and OrderBy. Query expressions usually start with the keyword “From”.To access standard LINQ query operators, the namespace System.Query should be imported by default. These expressions are written within a declarative query syntax which was C# 3.0.Below is an example to show a complete query operation which consists of data source creation, query expression definition and query execution.C#using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Operators{class LINQQueryExpressions{static void Main(){// Specify the data source.int[] scores = new int[] { 97, 92, 81, 60 };// Define the query expression.IEnumerable<int> scoreQuery = from score in scores where score > 80 select score;// Execute the query.foreach (int i in scoreQuery){Console.Write(i + " ");}Console.ReadLine();}}}When the above code is compiled and executed, it produces the following result:97 92 81Extension MethodsIntroduced with .NET 3.5, Extension methods are declared in static classes only and allow inclusion of custom methods to objects to perform some precise query operations to extend a class without being an actual member of that class. These can be overloaded also.In a nutshell, extension methods are used to translate query expressions into traditional method calls (object-oriented).Difference between LINQ and Stored ProcedureThere is an array of differences existing between LINQ and Stored procedures. These differences are mentioned below.∙Stored procedures are much faster than a LINQ query as they follow an expected execution plan.∙It is easy to avoid run-time errors while executing a LINQ query than in comparison to a stored procedure as the former has Visual Studio’s Intellisense support as well as full-type checking during compile-time.∙LINQ allows debugging by making use of .NET debugger which is not in case of stored procedures.∙LINQ offers support for multiple databases in contrast to stored procedures, where it is essential to re-write the code for diverse types of databases.∙Deployment of LINQ based solution is easy and simple in comparison to deployment of a set of stored procedures.Need for LINQPrior to LINQ, it was essential to learn C#, SQL, and various APIs that bind together the both to form a complete application. Since, these data sources and programming languages face an impedance mismatch; a need of short coding is felt.Below is an example of how many diverse techniques were used by the developers while querying a data before the advent of LINQ.SqlConnection sqlConnection = new SqlConnection(connectString);SqlConnection.Open();System.Data.SqlClient.SqlCommand sqlCommand = new SqlCommand();sqlCommand.Connection = sqlConnection;mandText = "Select * from Customer";LINQreturn sqlCommand.ExecuteReader (CommandBehavior.CloseConnection) Interestingly, out of the featured code lines, query gets defined only by the last two. Using LINQ, the same data query can be written in a readable color-coded form like the following one mentioned below that too in a very less time.Northwind db = new Northwind(@"C:\Data\Northwnd.mdf");var query = from c in db.Customers select c;Advantages of LINQLINQ offers a host of advantages and among them the foremost is its powerful expressiveness which enables developers to express declaratively. Some of the other advantages of LINQ are given below.∙LINQ offers syntax highlighting that proves helpful to find out mistakes during design time.∙LINQ offers IntelliSense which means writing more accurate queries easily.∙Writing codes is quite faster in LINQ and thus development time also gets reduced significantly.∙LINQ makes easy debugging due to its integration in the C# language.∙Viewing relationship between two tables is easy with LINQ due to its hierarchical feature and this enables composing queries joining multiple tables in less time.∙LINQ allows usage of a single LINQ syntax while querying many diverse data sources and this is mainly because of its unitive foundation.∙LINQ is extensible that means it is possible to use knowledge of LINQ to querying new data source types.∙LINQ offers the facility of joining several data sources in a single query as well as breaking complex problems into a set of short queries easy to debug.∙LINQ offers easy transformation for conversion of one data type to another like transforming SQL data to XML data.LINQ 2.Before starting with LINQ programs, it is best to first understand the nuances of setting up a LINQ environment. LINQ needs a .NET framework, a revolutionary platform to have a diverse kind of applications. A LINQ query can be written either in C# or Visual Basic conveniently.Microsoft offers tools for both of these languages i.e. C# and Visual Basic by means of Visual Studio. Our examples are all compiled and written in Visual Studio 2010. However, Visual Basic 2013 edition is also available for use. It is the latest version and has many similarities with Visual Studio 2012.Getting Visual Studio 2010 Installed on Windows 7Visual Studio can be installed either from an installation media like a DVD. Administrator credentials are required to install Visual Basic 2010 on your system successfully. It is vital to disconnect all removable USB from the system prior to installation otherwise the installation may get failed. Some of the hardware requirements essential to have for installation are the following ones.Hardware Requirements∙ 1.6 GHz or more∙ 1 GB RAM∙ 3 GB(Available hard-disk space)∙5400 RPM hard-disk drive∙DirectX 9 compatible video card∙DVD-ROM driveInstallation Steps∙Step 1: First after inserting the DVD with Visual Studio 2010 Package, click on Install or run program from your media appearing in a pop-up box on the screen.∙Step 2: Now set up for Visual Studio will appear on the screen. Choose Install Microsoft Visual Studio 2010.Step 3: As soon as you will click, it the process will get initiated and a set up window will appear on your screen. After completion of loading of the installation components which will take some time, click on Next button to move to the next step.∙Step 4: This is the last step of installation and a start page will appear in which simply choose “I have read and accept the license terms” and click on Next button.∙Step 5: Now select features to install from the options page appearing on your screen.You can either choose Full or Custom option. If you have less disk space than required shown in the disk space requirements, then go for Custom.∙Step 6: When you choose Custom option, the following window will appear. Select the features that you want to install and click Update or else go to step 7. However, it is recommended not to go with the custom option as in future, you may need the features you have chosen to not have.∙Step 7: Soon a pop up window will be shown and the installation will start which may take a long time. Remember, this is for installing all the components.Step 8: Finally, you will be able to view a message in a window that the installation has been completed successfully. Click Finish.Writing C# Program using LINQ in Visual Studio 20101.Start Visual Studio 2010 Ultimate edition and choose File followed by New Projectfrom the menu.2. A new project dialog box will appear on your screen.3.Now choose Visual C# as a category under installed templates and next chooseConsole Application template as shown in figure below.4.Give a name to your project in the bottom name box and press OK.5.The new project will appear in the Solution Explorer in the right-hand side of a newdialog box on your screen.6.Now choose Program.cs from the Solution Explorer and you can view the code inthe editor window which starts with ‘using System’.7.Here you can start to code your following C# program.using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace HelloWorld{class Program{static void Main(string[] args){Console.WriteLine("Hello World")Console.ReadKey();}}}8.Press F5 key and run your project. It is highly recommended to save the projectby choosing File Save All before running the project.Writing VB Program using LINQ in Visual Studio 20101.Start Visual Studio 2010 Ultimate edition and choose File followed by New Projectfrom the menu.2. A new project dialog box will appear on your screen.3.Now chose Visual Basic as a category under installed templates and next chooseConsole Application template.4.Give a name to your project in the bottom name box and press OK.5.You will get a screen with Module1.vb. Start writing your VB code here using LINQ. Module Module1Sub Main()Console.WriteLine("Hello World")Console.ReadLine()End SubEnd Module6.Press F5 key and run your project. It is highly recommended to save the projectby choosing File Save All before running the project.When the above code of C# or VB is compiled and run, it produces the following result: Hello WorldLINQ A set of extension methods forming a query pattern is known as LINQ Standard Query Operators. As building blocks of LINQ query expressions, these operators offer a range ofquery capabilities like filtering, sorting, projection, aggregation, etc.LINQ standard query operators can be categorized into the following ones on the basis of their functionality.∙Filtering Operators∙Join Operators∙Projection Operations∙Sorting Operators∙Grouping Operators∙Conversions∙Concatenation∙Aggregation∙Quantifier Operations∙Partition Operations∙Generation Operations∙Set Operations∙Equality∙Element OperatorsFiltering OperatorsFiltering is an operation to restrict the result set such that it has only selected elements satisfying a particular condition.Operator DescriptionC# QueryExpressionSyntaxVB QueryExpressionSyntaxWhere Filter values based on a predicatefunctionWhere WhereOfType Filter values based on their ability to be as a specified type Not Applicable Not Applicable3.Filtering Operators in LINQFiltering is an operation to restrict the result set such that it has only selected elements satisfying a particular condition.Operator DescriptionC# QueryExpressionSyntaxVB QueryExpressionSyntaxWhere Filter values based on a predicatefunction Where WhereOfType Filter values based on their ability to be as a specified type Not Applicable NotApplicableExample of Where − Query ExpressionC#using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Operators{class Program{static void Main(string[] args){string[] words = { "humpty", "dumpty", "set", "on", "a", "wall" };IEnumerable<string> query = from word in words where word.Length == 3 select word;foreach (string str in query)Console.WriteLine(str);Console.ReadLine();}}}VBModule Module1Sub Main()Dim words As String() = {"humpty", "dumpty", "set", "on", "a", "wall"}Dim query = From word In words Where word.Length = 3 Select wordFor Each n In queryConsole.WriteLine(n)NextConsole.ReadLine()End SubEnd ModuleWhen the above code in C# or VB is compiled and executed, it produces the following result:setJoin OperatorsJoining refers to an operation in which data sources with difficult to follow relationships with each other in a direct way are targeted.Operator DescriptionC# QueryExpressionSyntaxVB QueryExpression SyntaxJoin The operator join twosequences on basis ofmatching keysjoin … in … on …equals …From x In …, y In …Where x.a = y.aGroupJoin Join two sequences andgroup the matching elementsjoin … in … on …equals … into …Group Join … In … On…Join Operators in LINQJoining refers to an operation in which data sources with difficult to follow relationships with each other in a direct way are targeted.Operator DescriptionC# QueryExpression SyntaxVB QueryExpressionSyntaxJoin The operator join two sequences onbasis of matching keysjoin … in … on …equals …From x In…, y In …Where x.a= y.aGroupJoin Join two sequences and group thematching elementsjoin … in … on …equals … into …Group Join… In … On …Example of Join − Query ExpressionC#using System;using System.Collections.Generic;using System.Linq;namespace Operators{class JoinTables{class DepartmentClass{public int DepartmentId { get; set; }public string Name { get; set; }}class EmployeeClass{public int EmployeeId { get; set; }public string EmployeeName { get; set; }public int DepartmentId { get; set; }}static void Main(string[] args){List <DepartmentClass> departments = new List <DepartmentClass>();departments.Add(new DepartmentClass { DepartmentId = 1, Name = "Account" });departments.Add(new DepartmentClass { DepartmentId = 2, Name = "Sales" });departments.Add(new DepartmentClass { DepartmentId = 3, Name = "Marketing" });List <EmployeeClass> employees = new List <EmployeeClass>();employees.Add(new EmployeeClass { DepartmentId = 1, EmployeeId = 1, EmployeeName = "William" });employees.Add(new EmployeeClass { DepartmentId = 2, EmployeeId = 2, EmployeeName = "Miley" });employees.Add(new EmployeeClass { DepartmentId = 1, EmployeeId = 3, EmployeeName = "Benjamin" });var list = (from e in employees join d in departments one.DepartmentId equals d.DepartmentId select new{EmployeeName = e.EmployeeName,DepartmentName = });foreach (var e in list){Console.WriteLine("Employee Name = {0} , Department Name = {1}", e.EmployeeName, e.DepartmentName);}Console.WriteLine("\nPress any key to continue.");Console.ReadKey();}}}End of ebook previewIf you liked what you saw…Buy it from our store @ https://。
Table of ContentsAbout1 Chapter 1: Getting started with linq-to-sql2 Remarks2 Examples2 Installation or Setup2 Credits3AboutYou can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: linq-to-sqlIt is an unofficial and free linq-to-sql ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official linq-to-sql.The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners.Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to ********************Chapter 1: Getting started with linq-to-sql RemarksThis section provides an overview of what linq-to-sql is, and why a developer might want to use it. It should also mention any large subjects within linq-to-sql, and link out to the related topics. Sincethe Documentation for linq-to-sql is new, you may need to create initial versions of those relatedtopics.ExamplesInstallation or SetupInstalling linq-to-sql:Right-click the App_Code folder and then click Add New Item. The Add New Item dialog box is displayed. Under Visual Studio installed templates, select the LINQ to SQL Classes template and rename the file Tasks.dbml. Click Add.OR:Under VS2102, in your solution explorer, right click on your project, and select "Add/New Element". Then you find : C# -> Data -> "Linq to Sql classes" (depending on your Visual studio version) or you can select "Entity Data Model". An assistant should appear to guide you through the rest of the process.In your project classes you should then use your dataModel, and use Linq to make your requests. Read Getting started with linq-to-sql online: https:///linq-to-sql/topic/1594/getting-started-with-linq-to-sqlCredits。
1、LINQ表达式LINQ语言集成查询(Language Integrated Query)LINQ 最明显的“语言集成”部分是查询表达式。
查询表达式是使用C# 3.0 中引入的声明性查询语法编写的。
通过使用查询语法,您甚至可以使用最少的代码对数据源执行复杂的筛选、排序和分组操作。
您使用相同的基本查询表达式模式来查询和转换SQL 数据库、 数据集、XML 文档和流以及 .NET 集合中的数据。
下面的示例演示了完整的查询操作。
完整操作包括创建数据源、定义查询表达式,以及在foreach语句中执行查询。
class LINQQueryExpressions{staticvoid Main(){// Specify the data source.int[] scores = newint[] { 97, 92, 81, 60, 89, 45, 34, 78 };// Define the query expression.IEnumerable<int> scoreQuery =from score in scoreswhere score > 80select score;// Execute the query.foreach (int i in scoreQuery){Console.Write(i + " ");}}}// Output: 97 92 81 892、LINQ查询“查询”是指一组指令,这些指令描述要从一个或多个给定数据源检索的数据以及返回的数据应该使用的格式和组织形式。
查询不同于它所产生的结果。
通常,源数据会在逻辑上组织为相同种类的元素序列。
SQL 数据库表包含一个行序列。
与此类似, DataTable 包含一个DataRow 对象序列。
在XML 文件中,有一个XML 元素“序列”(不过这些元素按分层形式组织为树结构)。
内存中的集合包含一个对象序列。
从应用程序的角度来看,原始源数据的具体类型和结构并不重要。
应用程序始终将源数据视为一个IEnumerable<(Of <(T>)>) 或IQueryable<(Of<(T>)>) 集合。
在LINQ to SQL 中,源数据显示为一个IEnumerable<XElement>。
在LINQ to DataSet 中,它是一个IEnumerable<DataRow>。
在LINQ to SQL 中,它是您定义用来表示SQL 表中数据的任何自定义对象的IEnumerable 或IQueryable。
检索一个元素子集以产生一个新序列,但不修改单个元素。
然后,查询可以按各种方式对返回的序列进行排序或分组,如下面的示例所示(假定scores 是int[]):IEnumerable<int> highScoresQuery =from score in scoreswhere score > 80orderby score descendingselect score;●如上一个示例所述检索一个元素序列,但是将这些元素转换为具有新类型的对象。
例如,查询可以只从数据源中的某些客户记录检索姓氏。
或者,查询可以检索完整的记录,再使用它构建另一个内存中对象类型甚至XML 数据,然后生成最终的结果序列。
下面的示例演示了从int到string的转换。
请注意highScoresQuery 的新类型。
IEnumerable<string> highScoresQuery2 =from score in scoreswhere score > 80orderby score descendingselect String.Format("The score is {0}", score);●检索有关源数据的单一值。
IEnumerable<int> highScoresQuery3 =from score in scoreswhere score > 80select score;int scoreCount = highScoresQuery3.Count();3、查询表达式“查询表达式”是用查询语法表示的查询,是一流的语言构造。
它就像任何其他表达式一样,并且可以用在C# 表达式有效的任何上下文中。
查询表达式由一组用类似于SQL 或XQuery 的声明性语法编写的子句组成。
每个子句又包含一个或多个C# 表达式,而这些表达式本身又可能是查询表达式或包含查询表达式。
查询表达式必须以from 子句开头,并且必须以select 或group 子句结尾。
在第一个from 子句和最后一个select 或group 子句之间,查询表达式可以包含一个或多个下列可选子句:where、orderby、join、let 甚至附加的from 子句。
还可以使用into 关键字使join 或group 子句的结果能够充当同一查询表达式中附加查询子句的源。
3.1查询变量在LINQ 中,查询变量是任何存储查询而不是查询结果的变量。
更具体地说,查询变量始终是一个可枚举的类型,当在foreach 语句中或对其IEnumerator.MoveNext 方法的直接调用中循环访问它时,它将产生一个元素序列。
3.2查询变量的显式类型化和隐式类型化使用var 关键字指示编译器在编译时推断查询变量(或任何其他本地变量)的类型。
3.3开始查询表达式查询表达式必须以from 子句开头。
它同时指定了数据源和范围变量。
在对源序列进行遍历的过程中,范围变量表示源序列中的每个后续元素。
将根据数据源中元素的类型对范围变量进行强类型化。
在使用分号或延续子句退出查询之前,范围变量将一直位于范围中。
查询表达式可以包含多个from 子句。
当源序列中的每个元素本身就是集合或包含集合时,可使用附加的from 子句。
3.4结束查询表达式查询表达式必须以select子句或group子句结尾。
group子句使用group 子句可产生按照指定的键组织的组序列。
键可以采用任何数据类型。
select子句使用select 子句可产生所有其他类型的序列。
into延续可以在select 或group 子句中使用into 关键字来创建用于存储查询的临时标识符。
在下面的示例中,以一千万人口范围为界对countries 进行分组。
在创建这些组之后,使用附加子句筛选掉某些组,然后按升序对剩下的组进行排序。
若要执行这些附加操作,需要使用由countryGroup 表示的延续。
var percentileQuery =from country in countrieslet percentile = (int)country.Population / 10000000group country by percentile into countryGroupwhere countryGroup.Key >= 20orderby countryGroup.Keyselect countryGroup;3.5筛选、排序和联接在from 开始子句以及select 或group 结束子句之间,所有其他子句(where、join、orderby、from、let)都是可选的。
任何可选子句都可以在查询正文中使用零次或多次。
where 子句使用where 子句可以根据一个或多个谓词表达式筛选掉源数据中的某些元素。
orderby 子句使用orderby 子句可以按升序或降序对结果进行排序。
您还可以指定次要排序顺序。
join 子句使用join子句可以根据每个元素中指定键之间的相等比较,对一个数据源中的元素与另外一个数据源中的元素进行关联和/或组合。
在LINQ 中,联接操作是针对其元素具有不同类型的对象序列执行的。
在联接两个序列之后,必须使用select或group语句指定要存储到输出序列中的元素。
还可以使用匿名类型将每组关联元素中的属性组合为输出序列的新类型。
let 子句使用let子句可以将表达式(如方法调用)的结果存储到新的范围变量中。
3.6查询表达式中的子查询查询子句本身可能包含一个查询表达式,该查询表达式有时称为“子查询”。
每个子查询都以它自己的from 子句开头,该子句不一定指向第一个from 子句中的同一数据源。
var queryGroupMax =from student in studentsgroup student by student.GradeLevel into studentGroupselectnew{Level = studentGroup.Key,HighestScore =(from student2 in studentGroupselect student2.Scores.Average()).Max()};注意:在LINQ 文档中,存储查询的变量在其名称中包含单词“query”,而存储实际结果的变量在其名称中不包含单词“query”。
4、BT.SaaS.UI.WidgetFramework中LINQ 的使用以BT.SaaS.UI.WidgetFramework.DataAccess的DatabaseHelper类为例:定义连接字符串publicconststring ConnectionStringName ="DashboardConnectionString";定义ApplicationIDpublicconststring ApplicationID ="fd639154-299a-4a9d-b273-69dc28eb6388"; publicreadonlystatic Guid ApplicationGuid = new Guid(ApplicationID); 定义最大行数,防止查询大量结果导致服务器阻塞publicconstint MAX_ROWS = 1000;publicstatic DashboardDataContext GetDashboardData(){return GetDashboardData(true, MAX_ROWS);}重载GetDashboardData()方法publicstatic DashboardDataContext2 GetDashboardData(bool readOnly, int maxRowsAllowedToAffect){读取数据库连接配置var db =new DashboardDataContext2(ConfigurationManager.ConnectionStrings[ ConnectionStringName].ConnectionString);设置事物隔离级别为READ UNCOMMITTEDif (readOnly){db.Connection.Open();db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SET NOCOUNT ON; SET ROWCOUNT " + maxRowsAllowedToAffect);}设置事物隔离级别,防止在提交事务之前记录受其他用户的影响,避免了幻觉读else{db.Connection.Open();db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; SET ROWCOUNT " + maxRowsAllowedToAffect);}返回db 连接对象return db;}更新操作publicstaticvoid Update<T>(T obj, Action<T> detach,Action<T>update) where T : class{using (var db = GetDashboardData(false, 1)){detach(obj);db.GetTable<T>().Attach(obj);update(obj);db.SubmitChanges();}}更新所有publicstaticvoid UpdateAll<T>(List<T> items, Action<T> detach, Action<T> update) where T : class{using (var db = GetDashboardData(false, items.Count)){Table<T> table = db.GetTable<T>();foreach (T item in items){detach(item);table.Attach(item);update(item);}db.SubmitChanges();}}删除操作publicstaticvoid Delete<T>(T entity) where T : class,new() {using (var db = GetDashboardData(false, 1)){Table<T> table = db.GetTable<T>();table.Attach(entity);table.DeleteOnSubmit(entity);db.SubmitChanges();}}添加操作publicstaticvoid Insert<T>(T obj) where T : class{using (var db = GetDashboardData(false, 1)){db.GetTable<T>().InsertOnSubmit(obj);db.SubmitChanges();}}如何使用DatabaseHelper示例1:Insert方法protectedoverride ActivityExecutionStatusExecute(ActivityExecutionContext executionContext){using (var db = DatabaseHelper.GetDashboardData()){Widget w = db.Widgets.Single(a => a.ID == WidgetId);WidgetInstance wi = new WidgetInstance();wi.Title = ;wi.PageId = PageId;wi.CreatedDate = stUpdate = DateTime.Now;wi.VersionNo = 1;wi.State = string.Empty;wi.WidgetId = w.ID;wi.Expanded = true;wi.State = w.DefaultState;DatabaseHelper.Insert<WidgetInstance>(wi);this.NewWidget = wi;}return ActivityExecutionStatus.Closed;}示例2:Update 方法protectedoverride ActivityExecutionStatusExecute(ActivityExecutionContext executionContext){DatabaseHelper.Update<WidgetInstance>(this.WidgetInstance, (wi) => wi.Detach(),(wi) => wi.State = this.State);return ActivityExecutionStatus.Closed;}5、LINQ 用法示例。