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 的操作 ...
随机推荐
- LeetCode150:Evaluate Reverse Polish Notation
题目: Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are + ...
- 唯品会osp简介(转)
转自 https://blog.csdn.net/panyongcsd/article/details/58617810 公司(VIP)从2015年开始在内部推动Venus框架的使用,这是一款基于Ap ...
- maven仓库地址配置
# 背景 maven中央存库在国外,访问缓慢,一般国内镜像,这里推荐阿里云的 http://maven.aliyun.com/nexus/content/groups/public 我之前采用的方式是 ...
- [C#学习笔记]类型对象指针和同步块索引
写在前面 看<CLR via C#>第四章时,看到了类型对象指针和同步块索引这两个概念,不知如何解释,查看过相关资料之后,在此记录. 类型对象指针 <CLR via C#>中的 ...
- MSSQL数据表生成模型
MSSQL数据表生成模型 http://pan.baidu.com/s/1mhBAapy
- 区别script中的type=”text/javascript”和language=”Javascript”
内容提要 在制作网页的时候,往往需要在页面中使用客户端能够运行的JS代码,因此,都需要添加引用.JS引用一般有type="text/javascript"和language=&qu ...
- disruptor调优方法
翻译自disruptor在github上的文档,https://github.com/LMAX-Exchange/disruptor/wiki/Getting-Started Basic Tuning ...
- 理解js事件冒泡事件委托事件捕获
js事件冒泡 javascript的事件传播过程中,当事件在一个元素上出发之后,事件会逐级传播给先辈元素,直到document为止,有的浏览器可能到window为止,这就是事件冒泡现象. <di ...
- HttpClient和HttpURLConnection的使用和区别(上)
转自:点击打开链接 相信很多Android开发者碰到涉及到Http协议的需求时,都和我一样在犹豫是使用HttpClient还是使用HttpURLConnection呢.我在网上也搜索了很多文章,来分析 ...
- Python shutil模块(目录和文件操作)
import shutil #导入shutil模块 copyfileobj方法 将类文件对象fsrc的内容复制到类文件对象fdst shutil.copyfileobj(fsrc, fdst[, le ...