语言继承查询(Language Integrated Query, LINQ),在C#编程语言中集成了查询语法,可以用相同的语法访问不同的数据源,LINQ提供了不同数据源的抽象层,所以可以使用相同语法。

public class Book
{
public int Id { get; set; }
/// <summary>
/// 书名
/// </summary>
public string BookName { get; set; }
/// <summary>
/// 作者id
/// </summary>
public int AutherId { get; set; }
/// <summary>
/// 类型
/// </summary>
public string Type { get; set; }
/// <summary>
/// 售价
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// 销量
/// </summary>
public int Sales { get; set; }
}
public class Auther
{
public int Id { get; set; }
/// <summary>
/// 作者
/// </summary>
public string AutherName { get; set; }
}
public class Library
{
public string Address { get; set; }
/// <summary>
/// 书本
/// </summary>
public List<Book> BookList { get; set; }
}

1、条件查询(Where)

 var query = from book in bookList
where book.Price >
orderby book.Sales descending,book.BookName
select book;
//等同于
var query = bookList.Where(n => n.Price > ).OrderByDescending(g => g.Sales).ThenBy(y => y.BookName);

  需要注意的是,延迟查询

var ary = new List<string>(){ "Aa", "Bb", "Cc"};

var a1 = ary.Where(n => n.Contains("a"));//["Aa"]

ary.Add("Ga");

a1;//["Aa", "Ga"]

  解决这个问题,只需要用 ToList();

var ary = new List<string>(){ "Aa", "Bb", "Cc"};

var a1 = ary.Where(n => n.Contains("a")).ToList();//["Aa"]

ary.Add("Ga");

a1;//["Aa"]

  索引筛选

//销量大于50且为奇数行
var query = bookList.Where((n, index) => n.Sales > && index% != );

2、复合查询(SelectMany)

//查找所有图书馆中的小说
var query = from library in libraryList
from book in library.BookList
where book.Type == "小说"
select book; //等同于
query = libraryList.SelectMany(n => n.BookList).Where(g => g.Type == "小说"); //组织返回结果
query = libraryList.SelectMany(n => n.BookList, (n, g) => new {n.Address, g.BookName, g.Sales}).Where(y => y.Sales > );

3、集合连接

//内连接
var query1 = from book in bookList
     join auther in autherList on book.AutherId equals auther.Id
     select new { book.BookName, auther.AutherName };
//组连接
var query2 = from auther in autherList
   join book in bookList on auther.Id equals book.AutherId into items
   select new { auther.AutherName, Books = items };
//左外连接
var query3 = from book in bookList
join auther in autherList on book.AutherId equals auther.Id into items
from auther in items.DefaultIfEmpty()
select new
{
book.BookName,
AutherName = auther == default(Auther) ? "无" : auther.AutherName
};
//多条件连接
var query4 = from book in bookList
join auther in autherList on new {name = book.BookName, id = book.AutherId} equals new {name = auther.AutherName, id = auther.Id}
select book;

4、排序(OrderBy、ThenBy)

var query = from book in bookList
orderby book.Sales descending, book.AutherId, book.Price descending
select book;
//等同于
query = bookList.OrderByDescending(n => n.Sales).ThenBy(g => g.AutherId).ThenByDescending(y => y.Price);

5、分组(GroupBy)

//单一条件分组
var query = from book in bookList
group book by book.Type into bs
select bs.First();
//等同于
query = bookList.GroupBy(n => n.Type).Select(g => g.First()); //多条件分组
var query = from book in bookList
group book by new { book.Type, book.AutherId } into bs
select new
{
Type = bs.First().Type,
AutherId = bs.First().AutherId,
Count = bs.Count()
};
//等同于
query = bookList.GroupBy(n => new {n.Type, n.AutherId}).Select(g => new
{
Type = g.First().Type,
AutherId = g.First().AutherId,
Count = g.Count()
});

6、合并与分区(Zip、Take、Skip)

int[] numbers = { , ,  };
string[] words = { "One", "Two", "Three", "Four" };
//元素依次组合,长度为较小的集合
IEnumerable<string> zip = numbers.Zip(words, (n, g) => n + "=" + g);//["1=One", "2=Two", "3=Three"] //跳过集合的前n个元素
var skip = words.Skip();//["Four"]
//获取集合的前n个元素,有延迟
var take = numbers.Take();//[1, 2] int pageSize = ;//每页容量
int pageNum = ;//页数
var page = words.Skip(pageSize * pageNum).Take(pageSize);//["One", "Two", "Three"]

7、集合操作(Distinct、Union、Concat、Intersect、Except)

int[] ary1 = {, , , , };
int[] ary2 = {, , , , , }; //合并,自动去重
var union = ary1.Union(ary2);//1, 2, 3, 4, 5, 6, 7, 10
//合并,不会去重
var concat = ary1.Concat(ary2);//1, 2, 2, 4, 5, 3, 5, 5, 6, 10, 7
//去重
var distict = ary1.Distinct();//1, 2, 4, 5
//取交集,自动去重
var intersect = ary1.Intersect(ary2);//5
//取补集,自动去重
var except = ary1.Except(ary2);//1, 2, 4

8、类型筛选(ofType)

object[] data = { "one",  ,  ,"three"};
var query = data.ofType<string>();

9、聚合操作符(Count、Sum、Min、Max、Average、Aggregate)

//个数
var count = bookList.Count(n => n.Sales > );
//求和
var sum = bookList.Sum(n => n.Price);
//最小值
var min = bookList.Min(n => n.Sales);
//最大值
var max = bookList.Max(n => n.Price);
//平均值
var average = bookList.Average(n => n.Sales);
//累加,总销量
var aggregate1 = bookList.Select(n => n.Sales).Aggregate((g, y) => g + y);
//累加,初始值
var aggregate2 = bookList.Select(n => n.Sales).Aggregate(, (g, y) => g + y);
//累加,初始值,结果处理
var aggregate3 = bookList.Select(n => n.Sales).Aggregate(, (g, y) => g + y, result => result/);

10、转换操作符 (ToArray、ToDictionary、ToList、ToLookup、Cast)

Book[] ary = bookList.ToArray();

List<Book> list = bookList.ToList();

Dictionary<int, Book> dic = bookList.ToDictionary<Book, int>(n => n.Id);

//转换成LookUp集合,key-以key分组的内部集合
ILookup<string, Book> look = bookList.ToLookup(n => n.Type); IEnumerable<Book> cast = ary.Cast<Book>();

【Linq】常用语法汇总的更多相关文章

  1. Angular学习资料大全和常用语法汇总(让后端程序员轻松上手)

    前言: 首先为什么要写这样的一篇文章呢?主要是因为前段时间写过一些关于Angualr的相关实战文章,有些爱学习的小伙伴对这方面比较感兴趣,但是又不知道该怎么入手(因为认识我的大多数小伙伴都是后端的同学 ...

  2. sql 常用语法汇总

    Sql常用语法 SQL分类: DDL—数据定义语言(CREATE,ALTER,DROP,DECLARE) DML—数据操纵语言(SELECT,DELETE,UPDATE,INSERT) DCL—数据控 ...

  3. python3+selenium常用语法汇总

    Selenium常用语法总结 一.Selenium常用定位语法 1.元素定位 (1)ID定位元素: find_element_by_id(‘’) (2)通过元素的类名称定位元素: find_eleme ...

  4. 【.NET基础】Linq常用语法代码演示

    前言:前言不重要,linq入门常用的语法,linq语法可以用来写操作集合.数据库表集合等等几乎所有集合类型的操作.下面就写几个案例(以List集合来做的),看代码和运行结果即可. 本文演示环境:VS2 ...

  5. Linq常用语法详细

    1.简单的linq语法 //1 var ss = from r in db.Am_recProScheme select r; //2 var ss1 = db.Am_recProScheme; // ...

  6. SQL SERVER常用语法汇总

    阅读目录 一.SQL分类 二.基础语句 三.sql技巧 四.(MS SQL Server)SQL语句导入导出大全 回到目录 一.SQL分类 DDL—数据定义语言(CREATE,ALTER,DROP,D ...

  7. Groovy常用语法汇总

    基本语法 1.Grovvy的注释分为//和/**/和java的一样. 2.Grovvy语法可以不已分号结尾. 3.单引号,里面的内容严格的对应java中的String,不对$符号进行转义. def s ...

  8. SringBoot整合velocity及常用语法

    项目地址:https://github.com/chywx/springboot-velocity 背景 由于公司业务面向的是非洲市场 那边有些国家智能机并未普及,像乌干达地区还是以功能机为主 为了支 ...

  9. 20145222《信息安全系统设计基础》Linux常用命令汇总

    学习Linux时常用命令汇总 通过Ctrl+f键可在该网页搜索到你想要的命令. Linux中命令格式为:command [options] [arguments] //中括号代表是可选的,即有些命令不 ...

随机推荐

  1. Python面试题目--汇总

    原文链接-https://github.com/taizilongxu/interview_python Python语言特性 1 Python的函数参数传递 2 Python中的元类(metacla ...

  2. UVa 442 Matrix Chain Multiplication(栈的应用)

    题目链接: https://cn.vjudge.net/problem/UVA-442 /* 问题 输入有括号表示优先级的矩阵链乘式子,计算该式进行的乘法次数之和 解题思路 栈的应用,直接忽视左括号, ...

  3. UIKit 框架之UIControl

    前面的UIWebView.UIImageView这些都是视图,显示为主,与用户交互较少,最多也就是通过UIResponder与用户交互.但这样会很麻烦,还要判断点击次数等等问题,那问题就来了:OC中怎 ...

  4. AutoMapper之集合和数组映射

    9.集合和数组映射 在项目中,集合和数组使用的很多的,继续下来就讲讲他们的映射,很简单. /// <summary> /// 源对象 /// </summary> public ...

  5. sql 整理积累

    ) AS t1 LEFT JOIN (SELECT * FROM dbo.xcqy2017_News_Classification) AS t2 ON t2.Ncid = t1.Ncid left j ...

  6. 【移入移出事件练习】【菜单】【选项卡】 -------this使用

    鼠标移入移出事件练习 建一个长100x100的红色 div,鼠标移入变为200x200绿色 .a { width:100px; height:100px; background-color:red ; ...

  7. SpringBoot整合Netty

    总体来说只需要三个步骤,下面详细介绍 第一步 创建SpringBoot工程snetty 第二步 创建子模块也就是ModuleClient,Server,均为SpringBoot工程 第三步 将服务器端 ...

  8. ERP、CRM、CMS

    ERP: 全称:Enterprise Resource Planning 解释:企业资源计划. ERP 是一种主要面向制造行业进行物质资源.资金资源和信息资源集成一体化管理的企业信息管理系统.ERP ...

  9. 设计模式原则(1)--Single Responsibility Principle(SRP)--单一职责原则

    1.定义: 不要存在多于一个导致类变更的原因.通俗的说,即一个类只负责一项职责.  2.使用场景: 如果类A有两个职责:d1,d2.当职责d1需要修改时,可能会导致原本运行正常的职责d2功能产生问题. ...

  10. js-ES6学习笔记-Iterator

    1.遍历器(Iterator)是一种接口,为各种不同的数据结构提供统一的访问机制.任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员). 2.Iterator ...