• 查询对象(上例中为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简单使用的更多相关文章

  1. webform(八)——LinQ简单增、删、改、查

    一.简单介绍 1.LinQ to Sql类(NET Language Integrated Query (LINQ) ) LINQ定义了大约40个查询操作符,如select.from.in.where ...

  2. LinQ简单增、删、改、查

    一.简单介绍 1.LinQ to Sql类(NET Language Integrated Query (LINQ) ) LINQ定义了大约40个查询操作符,如select.from.in.where ...

  3. C# 基础知识系列- 6 Lambda表达式和Linq简单介绍

    前言 C#的lambda和Linq可以说是一大亮点,C#的Lambda无处不在,Linq在数据查询上也有着举足轻重的地位. 那么什么是Linq呢,Linq是 Language Intergrated ...

  4. LinQ 简单使用

    LinQ: 1.LinQ to Sql类(NET Language Integrated Query (LINQ) ) LINQ定义了大约40个查询操作符,如select.from.in.where以 ...

  5. LINQ 简单用法【1】

    LINQ:Language INtegrated Query,语言集成查询. 以下内容演示如何利用LINQ进行增加,修改,删除和查询操作,针对数据库. 首先创建Linq Class. 添加数据库信息, ...

  6. LINQ简单案例

    1.在visual studio 创建一个解决方案,新建一个控制台程序Kong 2.新建两个类,分别为Master 类和Kongfu类  Master类中包含成员如下,并重写ToString方法 na ...

  7. Entity Framework Linq 简单笔记

    类型查询 public class bbb:xxx {} var items = from c in context.Dbset<xxx>    where c is bbb   sele ...

  8. Entify Framewrok - LINQ简单使用

    1.如何使用Join: http://www.devcurry.com/2011/01/join-example-in-linq-and-c.html

  9. linQ学习笔记之一

    linq解决的问题 1.编程语言中的数据类型与数据库中的数据类型形成的两套体系 2.SQL编码体验落后 3.SQL和XML都有各自的查询语言,而对象没有自己的查询语言 linq简单的集合查询和fore ...

随机推荐

  1. HTTP、TCP、 UDP、 IP 、 Socket的关系

    TCP和UDP协议是传输协议,IP是网络层协议.传输协议和网络层协议主要解决数据如何在网络中传输,或者说TCP/IP 定义了电子设备如何连入因特网,以及数据如何在它们之间传输的标准.TCP负责发现传输 ...

  2. Material Design 之 TabLayout 使用

    记录 (非常详细的 TabLayout用法), 学习 http://www.jianshu.com/p/13f334eb16ce

  3. 自己封装的ASP.NET的MYSQL的数据库操作类

    /** * 作者:牛腩 * 创建时间:2010年3月7日17时35分 * 类说明:对MYSQL数据库的操作类 */ using System; using System.Data; using MyS ...

  4. 【专题】数位DP

    [资料] ★记忆化搜索:数位dp总结 之 从入门到模板 by wust_wenhao 论文:浅谈数位类统计问题 数位计数问题解法研究 [记忆化搜索] 数位:数字从低位到高位依次为0~len-1. 高位 ...

  5. 【洛谷 P3227】 [HNOI2013]切糕(最小割)

    题目链接 每层每个位置向下一层这个位置连边,流量为下一层这个位置的\(f\),源点向第一层连,流量第一层每个位置的费用,最后一层向汇点连,流量\(INF\). 这样就得到了\(P*Q\)条链,不考虑\ ...

  6. 2017ACM暑期多校联合训练 - Team 6 1001 HDU 6096 String (字符串处理 字典树)

    题目链接 Problem Description Bob has a dictionary with N words in it. Now there is a list of words in wh ...

  7. H5调试工具 - weinre远程调试工具

    weinre 简介 weinre 是一款类似于firebug 和Web Inspector的网页调试工具, 它的不同之处在于可以用于进行远程调试,比如调试手机上面的网页. 安装 weinre(运行在n ...

  8. python3爬虫.1.简单的网页爬虫

    此为记录下我自己的爬虫学习过程. 利用url包抓取网页 import urllib.request #url包 def main(): url = "http://www.douban.co ...

  9. python基础===100盏灯的问题

    闪存里有人这样提问这样: 第一轮操作所有电灯,第二轮操作第2盏,第4盏开关,以此类推,第三轮改变编号为3的倍数的电灯,第3盏,第6盏,如果原来那盏灯是亮的,就熄灭它,如果原来是灭的,就点亮它,以此类推 ...

  10. URAL题解三

    URAL题解三 URAL 1045 题目描述:有\(n\)个机场,\(n-1\)条航线,任意两个机场有且只有一种方案联通.现有两个恐怖分子从\(m\)号机场出发,第一个人在机场安装炸弹,乘坐飞机,引爆 ...