Linq学习笔记(一) -- 初识Linq

目录

什么是Linq

语言集成查询(LINQ)是一组技术的名称,而对于编写查询的开发人员来讲,LINQ最明显的语言集成部分就是查询表达式。它是使用C# 3.0中引入的声明性查询语法编写的,有了它,使得你可以使用非常简单的代码对各种数据源进行复杂的筛选、排序、分组等操作。
您可以使用同一个基本查询表达式来查询和转换SQL数据库、ADO.NET数据集、XML文档和流以及.NET集合中的数据。 ————LINQ查询表达式(C#编程指南)

由此可知,Linq使得在对象领域和数据领域为我们搭建了一座桥梁,是检索数据的集大成者。以往我们对数据库、XML、集合需要分别学习对应的知识;例如SQL脚本、对xml文件的操作以及对各种数据结构的集合的方法调用等;而有了Linq,使得我们可以通过Linq查询表达式就可以很方便的游走于各类数据源之间,而且Linq的优点还不止于此。

查询表达式

我们来看看Linq的查询表达式结构图:
Linq语法结构图

查询表达式的概述:

  • 查询表达式可用于查询和转换来自任意支持 LINQ 的数据源中的数据
  • 查询表达式中的变量都是强类型的,但许多情况下您不需要显式提供类型,因为编译器可以推断类型
  • 一些聚合方法如Count、Max等,没有等效的查询表达式子句,因此必须表示为方法调用
  • 查询表达式可以编译为表达式树或委托,具体取决于查询所应用到的类型。 IEnumerable 查询编译为委托。 IQueryable 和 IQueryable 查询编译为表达式树
  • 拥有延迟执行的特点

检索数据集合

我们先来写两个小例子,看看Linq的查询表达式是如何帮助我们检索数据的

int[] numbers = new int[] { 1, 21, 53, 4, 6435, 32, 6 };
var result = from n in numbers
             where n > 50
             select n;
foreach (var item in result)
{
     Console.WriteLine(item);
}
//输出结果:53,6435
//这里numbers换成任意支持Linq的数据集合都可以,比如List<int>

我们再看一个Dictionary的小例子

Dictionary<int, string> dics = new Dictionary<int, string>();
dics.Add(1, "2");
dics.Add(3, "4");
dics.Add(5, "6");
dics.Add(7, "8");

var resultDic = from n in dics
              where n.Key >= 5
              select n;
foreach (var item in resultDic)
{
     Console.WriteLine(item.Value);
}
//输出结果:6,8

匿名类型

匿名类型的其他优点我们另做讨论,咱们先只在Linq中做个小例子,可以将数据源转换为我们需要的类型结构
代码示例如下:

//假设数据源为产品类
public class Product
{
    public double Price { get; set; }
    public string Name { get; set; }
}

//我们再新建一个数据集合
List<Product> products = new List<Product>()
{
   new Product(){ Price = 2000.0, Name = "CPU"},
   new Product(){ Price = 300.0, Name = "GPU"},
};

var result = from p in products
             select new { Info = string.Format("产品名称为:{0},它的价格是:{1}", p.Name, p.Price) };
//输出结果为:
//产品名称为:CPU,它的价格是:2000
//产品名称为:GPU,它的价格是:300

延迟执行

Linq的查询操作分为三个部分
1.获取数据源
2.创建查询
3.执行查询

这也是Linq延迟执行的关键所在,就是将查询语句的创建与执行分开管理
以我们第一个简单的例子来说

//第一步获取数据源(XML、SQL皆可)
int[] numbers = new int[] { 1, 21, 53, 4, 6435, 32, 6 };
//第二步创建查询
//这里并没有执行对数据的真实筛选,可以理解为只是编译了查询命令
//比如这里的result变量可以看成是SQL语句:
//select * from numbers where n > 50,但是并未执行,类似视图
var result = from n in numbers
             where n > 50
             select n;

 //第三步执行查询,当对数据源执行遍历或者需要读取数据的时候,才会执行
foreach (var item in result)
{
     Console.WriteLine(item);
}

对元素执行聚类函数或转换函数等会使得对Linq表达式强制立即执行,比如Max、Average、First、ToList等

总结

综上所述,Linq帮助我们统一了访问方式,类似ORM框架对应各数据库的方式,让我们对数据的操作非常方便

感谢各位看官,小弟不才,如有不妥之处,还望指出,对我更是帮助

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LINQ中文学习资料和LINQ 随身参考手册,其中LINQ 随身参考手册是英文版的,但内容不错。 LINQ 随身参考手册介绍:   Ready to take advantage of LINQ with C# 3.0? This guide has the detail you need to grasp Microsoft’s new querying technology, and concise explanations to help you learn it quickly. And once you begin to apply LINQ, the book serves as an on-the-job reference when you need immediate reminders. All the examples in the LINQ Pocket Reference are preloaded into LINQPad, the highly praised utility that lets you work with LINQ interactively. Created by the authors and free to download, LINQPad will not only help you learn LINQ, it will have you thinking in LINQ. This reference explains: LINQ’s key concepts, such as deferred execution, iterator chaining, and type inference in lambda expressions The differences between local and interpreted queries C# 3.0′s query syntax in detail-including multiple generators, joining, grouping, query continuations, and more Query syntax versus lambda syntax, and mixed syntax queries Composition and projection strategies for complex queries All of LINQ’s 40-plus query operators How to write efficient LINQ to SQL queries How to build expression trees from scratch All of LINQ to XML’s types and their advanced useLINQ promises to be the locus of a thriving ecosystem for many years to come. This small book gives you a huge head start. “The authors built a tool (LINQPad) that lets you experiment with LINQ interactively in a way that the designers of LINQ themselves don’t support, and the tool has all kinds of wonderful features that LINQ, SQL and Regular Expression programmers alike will want to use regularly long after they’ve read the book.” -Chris Sells, Connected Systems Program Manager, Microsoft   About the Author   Joseph Albahari is a core C# design architect at Egton Medical Information Systems, the largest primary healthcare software supplier in the UK. He has been developing large-scale enterprise applications on .NET and other platforms for more than 15 years, working in medical, telecommunication and education industries. Joseph specializes in writing custom components and controls, and has designed application component frameworks for three companies.   Ben Albahari is currently involved in the bioinformatics business. He was a Program Manager at Microsoft for 5 years, where he worked on several projects, including the .NET Compact Framework and ADO.NET.   He was the cofounder of Genamics, a provider of tools for C# and J++ programmers, as well as software for DNA and protein sequence analysis. He is a co-author of C# Essentials, the first C# book from O’Reilly, and of previous editions of C# in a Nutshell.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值