C#语法之Linq查询基础二
上篇C#语法之Linq查询基础一基本把Linq介绍了一下,这篇主要是列举下它的几个常见用法。
在用之前先准备些数据,新建了两个类Student、Score,并通过静态方法提供数据。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace LinqDemo
{
public class Student
{
public string StuId { get; set; } public string Name { get; set; } public int Age { get; set; } public Student(string stuId, string name,int age)
{
StuId = stuId;
Name = name;
Age = age;
} public static List<Student> GetAllStudents()
{
List<Student> stus = new List<Student>() {
new Student("","xiaoming1",),
new Student("","xiaoming2",),
new Student("","xiaoming3",),
new Student("","xiaoming4",),
new Student("","xiaoming5",),
new Student("","xiaoming1",)
};
return stus;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace LinqDemo
{
public class Score
{
public string StuId { get; set; } public int Math { get; set; } public int English { get; set; } public int Chinese { get; set; } public Score(string stuId, int math, int english, int chinese)
{
StuId = stuId;
Math = math;
English = english;
Chinese = chinese;
} public static List<Score> GetAllScores()
{
List<Score> scores = new List<Score>()
{
new Score("",,,),
new Score("",,,),
new Score("",,,),
new Score("",,,),
new Score("",,,)
};
return scores;
} }
}
一、筛选
where 是筛选lamdba表达式的,OfType<TResult>是筛选TResult类型的
int[] a = new int[] { , , , , , , , , , };
var stus = Student.GetAllStudents().Where(p => p.StuId.Equals(""));
foreach (Student stu in stus)
{
Console.WriteLine("StuId:{0} Name:{1}", stu.StuId, stu.Name);
}
var result = a.Where((r, index) => r % == && index % == );
foreach (var s in result)
{
Console.WriteLine("{0}", s);
}
Console.WriteLine("--------------------------");
object[] data = { "one", , , "four", };
//OfType 可隐式转换 sting可隐式转换为int int不可隐式转换为string 所以不能直接写OfType<string>()
result = data.OfType<int>();
foreach (var s in result)
{
Console.WriteLine("{0}", s);
}

二、改变元素顺序
Orderby thenby来进行排序,thenby可以使用多次来多条件排序
//单个排序
int[] a = new int[] { , , , , , , , , , };
var result = a.OrderByDescending(p => p);
foreach (var s in result)
{
Console.WriteLine("{0}", s);
}

//多条件排序
var result = Student.GetAllStudents().OrderByDescending(p => p.StuId).ThenBy(p => p.Name); foreach (var s in result)
{
Console.WriteLine("StuId:{0} Name:{1}", s.StuId, s.Name);
}

翻转
对于上面的查询后面加一个Reverse()方法则会将结果翻转。
var result = Student.GetAllStudents().OrderByDescending(p => p.StuId).ThenBy(p => p.Name).Reverse();
foreach (var s in result)
{
Console.WriteLine("StuId:{0} Name:{1}", s.StuId, s.Name);
}

三、分组
分组常用作统计或查找重复。下面的例子就是查找姓名和年龄都相同的学生。
var result = from stu in Student.GetAllStudents()
group stu by new { stu.Name, stu.Age } into g
where g.Count() >
select new
{
g.Key.Name,
g.Key.Age
}; foreach (var s in result)
{
Console.WriteLine("Name:{0} Age:{1}", s.Name, s.Age);
}

四、连接
左连接
var result = from stu in Student.GetAllStudents()
join s in Score.GetAllScores() on stu.StuId equals s.StuId into joinStuScore
from p in joinStuScore.DefaultIfEmpty()
select new
{
StuId = stu.StuId,
Name = stu.Name,
Math = p == null ? : p.Math,
English = p == null ? : p.English,
Chinese = p == null ? : p.Chinese };
foreach (var s in result)
{
Console.WriteLine("StuId:{0} Name:{1} Math:{2} English:{3} Chinese:{4}", s.StuId, s.Name, s.Math, s.English, s.Chinese);
}

内连接
var result = from stu in Student.GetAllStudents()
join s in Score.GetAllScores() on stu.StuId equals s.StuId select new
{
StuId = stu.StuId,
Name = stu.Name,
Math = s.Math,
English = s.English,
Chinese = s.Chinese };
foreach (var s in result)
{
Console.WriteLine("StuId:{0} Name:{1} Math:{2} English:{3} Chinese:{4}", s.StuId, s.Name, s.Math, s.English, s.Chinese);
}

五、集合操作
下面是两个集合的交集、差集和并集,至于distinct这个之前有专门讲解。
int[] a = {,,, };
int[] b = { ,,,};
var result = a.Intersect(b);
foreach (var r in result)
{
Console.WriteLine(r);
}
Console.WriteLine("---------------");
result=a.Except(b);
foreach (var r in result)
{
Console.WriteLine(r);
}
Console.WriteLine("---------------");
result = a.Union(b);
foreach (var r in result)
{
Console.WriteLine(r);
}

六、分区
Take()和Skip()常用来做分页操作。下面的demo演示分页。
int pageSize = ;
int pageCount = (int)Math.Ceiling(Student.GetAllStudents().Count()/(double)pageSize);
for (int pageIndex = ; pageIndex < pageCount; pageIndex++)
{
Console.WriteLine("page {0}",pageIndex);
var result = (from s in Student.GetAllStudents().OrderBy(p => p.Age) select s).Skip(pageIndex * pageSize).Take(pageSize); foreach (var s in result)
{
Console.WriteLine("StuId:{0} Name:{1} Age:{2}", s.StuId, s.Name,s.Age);
}
}

七、限定符操作符
Any、All、Contains都是限定符操作符。Any是否有一个满足条件。ALL是所有元素都满足条件。Contains检查某个元素是否在集合中。都是返回布尔值。
bool anyFlag = Student.GetAllStudents().Any(p=>p.Name.Equals("xiaoming1") &&p.Age==);
bool allFlag = Student.GetAllStudents().Any(p =>p.Age == );
Student s = new Student("","xiaoming",);
bool containsFlag = Student.GetAllStudents().Contains(s);
Console.WriteLine("Any:{0} All:{1} Contains:{2}",anyFlag,allFlag,containsFlag);

八、聚合函数
Linq还提供了Count()、Sum()、Min()、Max()、Average()、Aggregate()一系列聚合函数。
C#语法之Linq查询基础二的更多相关文章
- C#语法之Linq查询基础一
Linq做.Net开发的应该都用过,有些地方很复杂的逻辑用Linq很方便的解决.对于Linq to object.Linq to xml.Linq to sql.Linq to Entity(EF)都 ...
- LINQ查询基础
一.什么是LINQ LINQ是Language Integrate Query的缩写,意为语言集成查询,是微软在.Net Framework 4.5版中推出的主要特性之一. 它为开发人员提供了统一的数 ...
- 二:MVC之LINQ查询语法
LINQ(Language Integrated Query)语言集成查询是一组用于c#和Visual Basic语言的扩展.它允许编写C#或者Visual Basic代码以操作内存数据的方式,查询数 ...
- [SQL] SQL 基础知识梳理(二) - 查询基础
SQL 基础知识梳理(二) - 查询基础 [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/5904824.html 序 这是<SQL 基础知识梳理( ...
- .NET LINQ查询语法与方法语法
LINQ 查询语法与方法语法 通过使用 C# 3.0 中引入的声明性查询语法,介绍性 LINQ 文档中的多数查询都被编写为查询表达式. 但是,.NET 公共语言运行时 (CLR) 本身并不具 ...
- LINQ基础(二)
本文主要介绍LINQ查询操作符 LINQ查询为最常用的操作符定义了一个声明语法.还有许多查询操作符可用于Enumerable类. 下面的例子需要用到LINQ基础(一)(http://www.cnblo ...
- linq查询语法和方法-簡單用法
來自:http://www.cnblogs.com/knowledgesea/p/3897665.html 1.简单的linq语法 //1 var ss = from r in db.Am_recPr ...
- C# LINQ学习笔记二:LINQ标准查询操作概述
本笔记摘抄自:https://www.cnblogs.com/liqingwen/p/5801249.html,记录一下学习过程以备后续查用. “标准查询运算符”是组成语言集成查询 (LINQ) 模式 ...
- C#基础:LINQ 查询函数整理
1.LINQ 函数 1.1.查询结果过滤 :where() Enumerable.Where() 是LINQ 中使用最多的函数,大多数都要针对集合对象进行过滤,因此Where()在LINQ 的操作 ...
随机推荐
- 关于Java_Web连接Oracle数据库
1.前提条件 1>装有Oracle数据库(因为连接的时候需要开启两项服务) 2>myeclipse或eclipse(支持WebProject的版本)开发环境,本机以myeclipse为例, ...
- 解决EF没有生成字段和表说明
找了很多资料,终于找到一篇真正能解决ef生成字段说明,注释的文章,收藏不了,于是转载 本文章为转载,原文地址 项目中使用了EF框架,使用的是Database-First方式,因为数据库已经存在,所以采 ...
- 记录.NET Core通过Docker部署到Linux
1.现在CentOS安装Docker环境(参考地址:https://docs.docker-cn.com/engine/installation/linux/docker-ce/centos/) 我这 ...
- 记录.NET Core部署到Linux之发布项目到Linux(2)
1.选择文件夹发布项目到本地,通过Xftp上传文件到/home/wwwroot下:下面具体介绍下 2.通过Xftp直接拖拽压缩包到linux下,通过命令cd /home/wwwroot目录下;然后输入 ...
- 用input标签 文件,多文件上传
单个文件,多个文件区别不大,只是需要把多个文件装在一个容器里面,循环遍历即可: 需要注意的 input 标签中name属性,一定要指定: 在这是 fileBase 需要确定method必须是pos ...
- 【cocos2d-x 仙凡奇缘-网游研发(2) 角色换线系统】
转载请注明出处:http://www.cnblogs.com/zisou/p/xianfan01.html 做一款游戏就先得制作好策划文档,和基本的人物世界构架的设计,然后架空在这样一个虚拟的世界中每 ...
- 双向链表的实现——java
实现类: /** * Java 实现的双向链表. * 注:java自带的集合包中有实现双向链表,路径是:java.util.LinkedList * * @author skywang * @date ...
- fail2ban
在 [DEFAULT] 全局配置中的ignoreip选项中添加被放行的ip地址:ignoreip = 127.0.0.1 172.17.1.218 网段可以加 127.0.0.1/8,用空格隔开就行. ...
- ReentrantReadWriteLock源码分析(一)
此处源码分析,主要是基于读锁,非公平机制,JDK1.8. 问题: 1.ReentrantReadWriteLock是如何创建读锁与写锁? 2.读锁与写锁的区别是什么? 3.锁的重入次数与获取锁的线程数 ...
- 初始化css文件
首先我们需要了解一下为什么需要公共样式(公共样式是为了初始化某些标签的默认值): 1. 因为浏览器的兼容问题,不同浏览器对有些标签的默认值是不同的,如果没对CSS初始化往往会出现浏览器之间的页面显示差 ...