Linq简单使用
- 查询对象(上例中为list变量)为IEnumerable<T>或IQueryable<T>类型
- 查询返回结果同样为IEnumerable<T>或IQueryable<T>类型
Linq 分为:Linq to objects、Linq to DataSets、Linq to SQL、Linq to Entities、Linq to XML五类。
简单使用
类型 查询变量 =
from 临时变量 in 集合对象或数据库对象
[where 条件表达式]
[order by 条件]
select 临时变量或临时变量中被查询的值
[group by]
① 普通查询:
// 数据源
int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Linq查询
var result =
from item in arr // 声明临时变量item,并说明其为数组arr中的元素,item
where item > 4
select item; // 将查询结果(item)添加到result中 // 遍历Linq查询结果,实际上是“Linq查询”是伴随foreach执行的,即在foreach执行前“Linq查询”不会执行
foreach(int i in result)
{
Console.Write(i); //输出56789
}
② 查询并排序:
int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var result =
from item in arr
where item > 4
orderby item descending // 降序排列
select item; foreach(int i in result) {
Console.Write(i); // 输出:98765
}
③ 类型转换:
int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var result =
from item in arr
where item > 4
select string.Format("值:{0} ", item); // 转化为String类型,并格式化 foreach(string i in result) { // 变量i更改为string类型
Console.Write(i); // 输出“值:5 值:6 值:7 值:8 值:8 ”
}
④ 查询单一值:
int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int result0 = (from item in arr where item > 4 select item).Count(); // 整个语句被一堆()抱起来,统计数目
int result1 = (from item in arr where item > 4 select item).Max(); // 查询最大值 Console.WriteLine(result0); //输出:5
Console.WriteLine(result1); //输出:9
from子查询
class Program
{
static void Main(string[] args)
{
// 创建一个类似二维数组的泛型变量arr,用于存储学生信息
List arr = new List
{
new Student {name = "李宁", scores = new List{11, 12, 34} },
new Student {name = "阿迪", scores = new List{11, 16, 34} },
new Student {name = "耐克", scores = new List{18, 12} },
}; // 查询学生分数大于15分的记录
var result =
from stu in arr // 声明临时变量stu
from sc in stu.scores // 声明临时变量sc用于“子查询”,
where sc > 15
select new {name = stu.name, score = sc}; // 将查询结果“投影”到一个新的对象中,该对象有name和score两个属性。 foreach (var s in result) {
Console.WriteLine(s.name + ":" + s.score);
}
}
}
class Student
{
public string name; // 学生姓名
public List scores; // 学生分数,一个学生可以有多个分数
}
输出结果:
李宁:34
阿迪:16
阿迪:34
耐克:18
上述示例,实际是每个学生都与其分数做了多次关联,并将查询结果存入新的对象(new {...})中。
关联多个数据源
// 定义数据源
char[] upper = { 'A', 'B', 'C' };
char[] lower = { 'x', 'y', 'z' }; // 关联两个数据源
var result0 =
from up in upper
from lo in lower
select new {upper = up, lower=lo}; foreach (var item in result0) {
Console.WriteLine(item.upper + " " + item.lower);
} // 关联两个数据源,并按条件筛选
var result1 =
from up in upper
from lo in lower
where up != 'B'
select new { upper = up, lower = lo }; foreach (var item in result1) {
Console.WriteLine(item.upper + " " + item.lower);
}
两次输出结果分别为:
分组
① 简单分组
class Program
{ static void Main(string[] args)
{
// 定义数据源
List<Product> arr = new List<Product>
{
new Product{name = "衬衫", price = 13.9m, cid = 1},
new Product{name = "短裤", price = 199.2m, cid = 1},
new Product{name = "奥迪", price = 1.6m, cid = 2},
new Product{name = "奔驰", price = 2.7m, cid = 2},
new Product{name = "歼十", price = 82.3m, cid = 3},
new Product{name = "播音", price = 91.3m, cid = 3},
}; var result =
from p in arr
group p by p.cid; // 遍历组别
foreach (var gp in result) {
Console.WriteLine("==============");
// 遍历每组成员
foreach (var pd in gp) {
Console.WriteLine("{0}-{1}-{2}", pd.name, pd.price, pd.cid);
}
} Console.Read();
}
}
class Product
{
public string name; // 商品名称
public decimal price; // 商品价格
public int cid; // 商品分类
}
此处的分组并非SQL中的分组,SQL中的分组主要用于分组统计。而此处的分组是将原来“一维的数据”按照一定规则分组成“二维的数据”,其输出结果:
② 对组对象处理
static void Main(string[] args)
{
// 定义数据源
List arr = new List
{
new Product{name = "衬衫", price = 13.9m, cid = 1},
new Product{name = "短裤", price = 199.2m, cid = 1},
new Product{name = "奥迪", price = 1.6m, cid = 2},
new Product{name = "奔驰", price = 2.7m, cid = 2},
new Product{name = "歼十", price = 82.3m, cid = 3},
new Product{name = "播音", price = 91.3m, cid = 3},
};
List classList = new List
{
new Pclass{cname="衣服", cid = 1},
new Pclass{cname="汽车", cid = 2},
new Pclass{cname="飞机", cid = 3},
}; var result =
from p in arr
// G实际上就是组,格式为<Vey, Values>格式
// Key为该分组的cid
// Values为该组元素集合
group p by p.cid into G from cls in classList
where G.Key == cls.cid // 关联组G和classList集合
select new {cname = cls.cname, cid = cls.cid, gplist = G}; foreach (var gp in result)
{
Console.WriteLine();
Console.WriteLine("组名:{0},分类id:", gp.cname, gp.cid);
foreach (var pd in gp.gplist)
{
Console.WriteLine("{0}-{1}-{2}", pd.name, pd.price, pd.cid);
}
}
}
}
class Pclass
{
public int cid; // 分类id
public string cname; // 分类名称
}
class Product
{
public string name; // 商品名称
public decimal price; // 商品价格
public int cid; // 商品分类
}
上述代码的关键在于对“into G”的理解,查询部分的执行过程为:
第一步执行分组,分出一个组(如cid=1组)后存入临时变量G中;然后执行第二步,将该分组G与classList集合关联,将符合条件的结果按照select指定格式存储。第一个分组处理完毕后,按照上述步骤处理第二个分组(cid=2),依次类推。
程序执行输出结果:
③对分组对象进行删除
static void Main(string[] args)
{
List sts = new List
{
new Student{id= 1, name="李宁", cid = 1},
new Student{id= 2, name="李娜", cid = 2},
new Student{id= 3, name="耐克", cid = 3},
new Student{id= 4, name="阿迪", cid = 2},
new Student{id= 5, name="奔驰", cid = 1},
new Student{id= 6, name="报名", cid = 3},
}; var result =
from s in sts
group s by s.cid into G
select new {
id = G.Key,
list = (
// 排除id为偶数的学生
from m in G
where (m.id % 2 != 0)
select m
)
}; foreach (var item in result) {
Console.WriteLine("Cid:{0}", item.id);
foreach (var s in item.list) {
Console.WriteLine("{0}-{1}-{2}", s.id, s.name, s.cid);
}
}
}
let 子句
用于在查询中创建一个新的临时变量
static void Main(string[] args)
{
// 定义数据源
List sts = new List
{
new Student{id= 1, name="李宁", cid = 1},
new Student{id= 2, name="李娜", cid = 2},
new Student{id= 3, name="耐克", cid = 3},
new Student{id= 4, name="阿迪", cid = 2},
new Student{id= 5, name="奔驰", cid = 1},
new Student{id= 6, name="报名", cid = 3},
}; var result =
from s in sts
let fullname = s.id + s.name
select string.Format("id:{0},全称:{1}", s.id, fullname); foreach (string i in result) {
Console.WriteLine(i);
}
}
Linq简单使用的更多相关文章
- webform(八)——LinQ简单增、删、改、查
一.简单介绍 1.LinQ to Sql类(NET Language Integrated Query (LINQ) ) LINQ定义了大约40个查询操作符,如select.from.in.where ...
- LinQ简单增、删、改、查
一.简单介绍 1.LinQ to Sql类(NET Language Integrated Query (LINQ) ) LINQ定义了大约40个查询操作符,如select.from.in.where ...
- C# 基础知识系列- 6 Lambda表达式和Linq简单介绍
前言 C#的lambda和Linq可以说是一大亮点,C#的Lambda无处不在,Linq在数据查询上也有着举足轻重的地位. 那么什么是Linq呢,Linq是 Language Intergrated ...
- LinQ 简单使用
LinQ: 1.LinQ to Sql类(NET Language Integrated Query (LINQ) ) LINQ定义了大约40个查询操作符,如select.from.in.where以 ...
- LINQ 简单用法【1】
LINQ:Language INtegrated Query,语言集成查询. 以下内容演示如何利用LINQ进行增加,修改,删除和查询操作,针对数据库. 首先创建Linq Class. 添加数据库信息, ...
- LINQ简单案例
1.在visual studio 创建一个解决方案,新建一个控制台程序Kong 2.新建两个类,分别为Master 类和Kongfu类 Master类中包含成员如下,并重写ToString方法 na ...
- Entity Framework Linq 简单笔记
类型查询 public class bbb:xxx {} var items = from c in context.Dbset<xxx> where c is bbb sele ...
- Entify Framewrok - LINQ简单使用
1.如何使用Join: http://www.devcurry.com/2011/01/join-example-in-linq-and-c.html
- linQ学习笔记之一
linq解决的问题 1.编程语言中的数据类型与数据库中的数据类型形成的两套体系 2.SQL编码体验落后 3.SQL和XML都有各自的查询语言,而对象没有自己的查询语言 linq简单的集合查询和fore ...
随机推荐
- 手脱JDPack
1.PEID查壳 JDPack 2.载入OD,入口是一个pushad入栈,可以使用ESP,下硬件访问断点,shift+F9 0040E000 > pushad ; //入口 0040E001 E ...
- poi复杂excel的实现
一:前言 最近帮一个朋友做excel的导出功能,对于我来说还是挺头疼,我看了下表格样式,对于我来说还是挺头疼的,想当年耗子刚刚出社会的时候做的第一份工作,第一份任务就是把把word转换为html,在这 ...
- HDU 2619 完全剩余类 原根
求有多少$i(<=n-1)$,使 $x^i \mod n$的值为$[1,n-1]$,其实也就是满足完全剩余类的原根数量.之前好像在二次剩余的讲义PPT里看到这个过. 直接有个定理,如果模k下有 ...
- LightOJ 1364 树形DP
52张扑克牌,问拿到指定数量的4个花色的最少次数期望是多少,其中拿到joker必须马上将其视作一种花色,且要使后续期望最小. 转移很容易想到,主要是两张joker的处理,一个状态除了普通的4个方向的转 ...
- 【IDEA】 Can't Update No tracked branch configured for branch master or the branch doesn't exist. To make your branch track a remote branch call, for example, git branch --set-upstream-to origin/master
IDEA点击GIT更新按钮时,报错如下: Can't UpdateNo tracked branch configured for branch master or the branch doesn' ...
- Spring Boot中使用Spring-data-jpa让数据访问更简单、更优雅
在上一篇Spring中使用JdbcTemplate访问数据库中介绍了一种基本的数据访问方式,结合构建RESTful API和使用Thymeleaf模板引擎渲染Web视图的内容就已经可以完成App服务端 ...
- windows下面安装Python和pip教程
第一步,先来安装Python.windows下面的Python安装一般是通过软件安装包安装而不是命令行,所以首先要在Python的官方主页上面下载最新的Python安装包.下载地址是:https:// ...
- 5-python的封装与结构 - set集合
目录 1 封装与解构 1.1 封装 1.2 解构 1.3 Python3的解构 2 set类型 2.1 set的定义 2.2 set的基本操作 2.2.1 增加元素 2.2.2 删除元素 2.2.3 ...
- 解读Linux命令格式(转)
解读Linux命令格式 环境 Linux HA5-139JK 2.6.18-164.el5 #1 SMP Tue Aug 18 15:51:48 EDT 2009 x86_64 x86_64 x8 ...
- Linux 删除文件后空间不释放【原创】
删除MySQL备份文件后,查找文件所在目录发现文件已经备删除了,但是空间没有释放,还是83% 解决方法: lsof|grep -i delete 发现进程还在,杀掉进程 kill -9 5377 再次 ...