C# LINQ学习笔记
LINQ,语言集成查询;
LINQ TO SQL,同EF,NHibernate一样,也是一种ORM框架;
1. 入门应用示例:
static public void LinqBasic()
{
var colors = new[] { "Red", "Orange", "Yellow", "Black", "Purple", "Grenn", "White", "Blue", "Hello World !" };
var query = from color in colors
orderby color ascending, color.Length descending
where color == "Red" || color.StartsWith("P") && color.Length >= || !color.Any()
select color; foreach (var color in query)
{
Console.WriteLine(color);
}
}
2. 限定符运算:
Any() //判断是否有元素满足某个条件
All()//判断是否所有的数据都满足某个条件
Contains//判断是否包含某个元素;
3. Set集合的用法:
主要测试了几中常见方法:Distinct(),Except(),Intersect()及Union()
static public void Set()
{
List<String> htsA = new List<String>() { "Red", "Red", "Black", "White", "White", "Blue" };
List<String> htsB = new List<String>() { "Red", "Red", "Black", "Black" }; IEnumerable<String> htsC = htsA.Distinct();
IEnumerable<String> htsD = htsA.Except(htsB);
IEnumerable<String> htsE = htsA.Intersect(htsB);
IEnumerable<String> htsF = htsA.Union(htsB); foreach (String ht in htsA)
{
Console.WriteLine(ht);
}
}
4. Skip()/SkipWhile() 及 Take()/TakeWhile()
Skip(n):跳过n元素开始读取;
SkipWhile(): 从第一个条件为false的地方开始读取元素,遇到第一个true条件则停止读取;
Take(n): 从第一个元素开始,读取n个元素
TakeWhile(); 从第一个条件为true的地方开始读取元素,遇到第一个false条件则停止读取;
static public void Skip()
{
var colors = new[] { "Red", "Orange", "Yellow", "Black", "Purple", "Grenn", "White", "Blue", "Hello World !" };
var res = colors.SkipWhile(n => n != "Black");
foreach (var color in res)
//foreach (var color in colors.Skip(5))
{
Console.WriteLine(color);
}
} static public void Take()
{
var colors = new[] { "Red", "Orange", "Yellow", "Black", "Purple", "Grenn", "White", "Blue", "Hello World !" };
var res = colors.TakeWhile(n => n != "Black");
foreach (var color in res)
//foreach (var color in colors.Take(5))
{
Console.WriteLine(color);
}
}
5. Select/SelectMany用法:
SelectMany:将嵌套列表合并为一个列表:
static public void Select()
{
var mat = new[] { new[] {,,,},
new[] {,,,},
new[] {,,,},
new[] {,,,}
}; var query_01 = mat.Select(n => n.ToList());
var query_02 = mat.SelectMany(n => n.ToList()); foreach (var val in query_01)
{
Console.WriteLine(val);
} foreach (var val in query_02)
{
Console.WriteLine(val);
}
}
6. Join/GroupJoin用法:
Join(param1,param2,param3,param4): param1:要联接的第一个集合;param2:第一个集合中与第二个集合的关联列;param3:第二个集合中与第一个集合的关联列;param4:返回列的集合(可以对返回列进行重命名)
Group join:适合返回有级别的列表
static public void Join()
{
List<Company> cmyList = new List<Company>
{
new Company {Id=,ComName="CMA"},
new Company {Id=,ComName="CMB"},
}; List<Employee> empList = new List<Employee>
{
new Employee {CompanyId=,EmpName="Jam",},
new Employee {CompanyId=,EmpName="Ke"},
new Employee {CompanyId=,EmpName="Lin"},
new Employee {CompanyId=,EmpName="SyEn"},
new Employee {CompanyId=,EmpName="Kate"}
}; var matJoin11 = cmyList.Join(empList, m => m.Id, n => n.CompanyId, (m, n) => new {CompanyName=m.ComName,EmployeeName=n.EmpName}).OrderBy(p => p.EmployeeName); var matJoin12 = from cmy in cmyList
join emp in empList on cmy.Id equals emp.CompanyId
select new { CompanyName = cmy.ComName, EmployeeName = emp.EmpName }; foreach (var val in matJoin11)
{
Console.WriteLine(val);
} foreach (var val in matJoin12)
{
Console.WriteLine(val);
} var matGJoin21 = cmyList.GroupJoin(empList, m => m.Id, n => n.CompanyId, (m, o) => new { CompanyName = m.ComName,EmployeeName=o.Select(n => n.EmpName)});
var matGJoin22 = (from cmy in cmyList
join emp in empList on cmy.Id equals emp.CompanyId into nt
select new
{
CompanyName = cmy.ComName,
EmployeeName = nt
}).ToList(); foreach (var val in matGJoin21)
{
Console.WriteLine(val.CompanyName+":");
foreach(var emp in val.EmployeeName)
{
Console.WriteLine("--"+emp);
}
} foreach (var val in matGJoin22)
{
Console.WriteLine(val.CompanyName + ":");
foreach (var emp in val.EmployeeName)
{
Console.WriteLine("--" + emp.EmpName);
}
}
}
运行结果:
7. Range()/Repeat()/SequenceEqual()
Range(param1,param2) param1:第一个值,默认第二个值为2,依次为3,4,5...; param2:需要生成的元素个数
Repeat()列表复制
SequenceEqual() 列表是否相等(元素个数,每个位置元素内容)的判断
static public void Range()
{
//Range(param1,param2) param1:第一个值,默认第二个值为2,依次为3,4,5...; param2:需要生成的元素个数
List<int> nl = Enumerable.Range(, ).Select(x => x + ).ToList();
foreach (int i in nl)
{
Console.WriteLine("{0}",i);
}
} static public void Repeat()
{
List<String> hts = new List<String>() { "Red", "Red", "Black", "White", "White", "Blue" };
var nht = Enumerable.Repeat(hts,).ToList().SelectMany(n => n.ToList());
foreach (var v in nht)
{
Console.WriteLine(v);
}
} //Enumerable.Empty:返回具有指定类型参数的空 IEnumerable<T>。 static public void SequenceEqual()
{
List<String> htA = new List<String>() { "Red", "Red", "Black", "White", "White", "Blue" };
List<String> htB = new List<String>() { "Red", "Red", "Black", "White", "White", "Blue" };
bool b = htA.SequenceEqual(htB);
Console.WriteLine(b);
}
8. 列表元素操作:First()/FirstOrDefault()/Last()/ElementAt()/Single()
static public void ElementOperation()
{
List<String> hts = new List<string>() { "Red", "Orange", "Yellow", "Black", "Purple", "Grenn", "White", "Blue"}; Console.WriteLine(hts.First());
Console.WriteLine(hts.FirstOrDefault(color => color.Length>));
Console.WriteLine(hts.Last());
Console.WriteLine(hts.ElementAt());
//Console.WriteLine(hts.Single(color => color.Length>5));
}static public void ElementOperation()
{
List<String> hts = new List<string>() { "Red", "Orange", "Yellow", "Black", "Purple", "Grenn", "White", "Blue"}; Console.WriteLine(hts.First());
Console.WriteLine(hts.FirstOrDefault(color => color.Length>));
Console.WriteLine(hts.Last());
Console.WriteLine(hts.ElementAt());
//Console.WriteLine(hts.Single(color => color.Length>5));
}
9. GroupBy用法:
static public void GroupBy()
{
List<String> hts = new List<String>() { "Red", "Red", "Black", "White", "White", "Blue" };
var query = from ht in hts group ht by ht.Substring(, );
foreach (var gp in query)
{
Console.WriteLine("Colors start with "+gp.Key);
foreach (var dt in gp)
{
Console.WriteLine(dt);
}
}
}
10. Union用法:
static public void Union()
{
var matA = new[] {
new[] {,,,},
new[] {,,,}
}; var matB = new[] {
new[] {,,,},
new[] {,,,}
}; var matJoin = matA.Union(matB); var v = matJoin.SelectMany(n => n.ToList()); foreach (var val in v)
{
Console.WriteLine(val);
}
}
11. 类型转换:
Cast():将IEnumerable的元素强制转换为指定的IEnumerable类型;
AsEnumerable():将其他类型转为IEnumerable<T>;
OfType():根据指定类型筛选IEnumerable的元素。
static public void TypeConvert()
{
var colors = new[] { "Red", "Black", "Green", "Purple", "White", "Blue" };
List<string> hts = colors.AsEnumerable().ToList(); foreach (string s in hts)
{
Console.WriteLine(s);
} Console.WriteLine("The int value in the list is as below:");
ArrayList ays = new ArrayList() { "Red", "Black", "Green", , "White", "Blue" };
List<int> sls = ays.OfType<int>().ToList();
foreach (int s in sls)
{
Console.WriteLine(s);
} Console.WriteLine("The new list after convert is as below:");
List<string> sls_new = ays.OfType<string>().ToList();
IEnumerable<string> ays_new = sls_new.Cast<string>();
foreach (string s in ays_new)
{
Console.WriteLine(s);
}
}
12.序列合并:
把两个序列合并为一个:
static public void Concat()
{
List<String> htA = new List<String>() { "Red", "Blue" };
List<String> htB = new List<String>() { "Black", "White" };
List<string> hts = htA.Select(x => x).Concat(htB.Select(y => y)).ToList(); foreach (string ht in hts)
{
Console.WriteLine(ht);
}
}
13. 聚合运算:
static public void Aggregate()
{
List<int> its = new List<int> { , , , , , , };
double avg = its.Average();
int max = its.Max();
int min = its.Min();
int cut = its.Count();
int sum = its.Sum(); Console.WriteLine("Average is {0};", avg);
Console.WriteLine("Max is {0};", max);
Console.WriteLine("Min is {0};", min);
Console.WriteLine("Count is {0};", cut);
Console.WriteLine("Sum is {0};", sum);
}
至此,关于Linq的基本用法几乎都在这里了,对于更多详细说明,请参见官方文档.
C# LINQ学习笔记的更多相关文章
- linq学习笔记
最近在学习linq的一些基础知识,看了c#高级编程及阅读了园子内部几篇优秀的博文,有所体会,感觉应该记录下来,作为以后复习使用.都是一些最基础的知识,大致分为三个部分:linq预备知识:linq查询: ...
- (转)Linq学习笔记
写在前面 最近在看Linq,在博客园看到这篇文章,写的通俗易懂,转来和大家一起做个分享.原文地址http://www.cnblogs.com/goscan/archive/2011/05/05/Lin ...
- C#之Linq学习笔记【转】
写在前面 其实在09年就已经学习过Linq了,并被她那优美的语法所吸引,只是现在所在的公司还在使用VS2005在.Net2.0的框架下面的开发,所以Linq也很久没有用过了,最近看部门的同事对这个有些 ...
- C# Linq 学习笔记
刚刚学习了 Siki老师 的C#教程Linq部分,以下是笔记 需要引用命名空间 using System.Linq; 然后我们需要准备数据 武林高手类 /// <summary> /// ...
- C# LINQ学习笔记一:走进LINQ的世界
本笔记摘抄自:https://www.cnblogs.com/liqingwen/p/5832322.html,记录一下学习过程以备后续查用. LINQ 简介: 语言集成查询(LINQ)是Vi ...
- LINQ 学习笔记(1)
学习资源参考 : http://www.cnblogs.com/lifepoem/archive/2011/12/16/2288017.html 常用方法是 Where, OrderBy, Selec ...
- C# LINQ学习笔记五:LINQ to XML
本笔记摘抄自:https://www.cnblogs.com/yaozhenfa/p/CSharp_Linq_For_Xml.html,记录一下学习过程以备后续查用. 一.生成xml 1.1创建简单的 ...
- C# LINQ学习笔记四:LINQ to OBJECT之操作文件目录
本笔记摘抄自:https://www.cnblogs.com/liqingwen/p/5816051.html,记录一下学习过程以备后续查用. 许多文件系统操作实质上是查询,因此非常适合使用LINQ方 ...
- C# LINQ学习笔记三:LINQ to OBJECT之操作字符串
本笔记摘抄自:https://www.cnblogs.com/liqingwen/p/5814204.html,记录一下学习过程以备后续查用. 一.统计单词在字符串中出现的次数 请注意,若要执行计数, ...
- C# LINQ学习笔记二:LINQ标准查询操作概述
本笔记摘抄自:https://www.cnblogs.com/liqingwen/p/5801249.html,记录一下学习过程以备后续查用. “标准查询运算符”是组成语言集成查询 (LINQ) 模式 ...
随机推荐
- Python基于VS2013 开发环境搭建 Hello World 10分钟搞定
1.先下载Python 安装 Next ->安装完成 2.以前安装过VS2013 打开VS2013 文件->新建项目 (此时如果没有Python Application,请点击里面的安装插 ...
- 编写高质量代码改善C#程序的157个建议——建议124:考虑在命名空间中使用复数
建议124:考虑在命名空间中使用复数 如果有一组功能相近的类型被分到了同一个命名空间想,可以考虑为命名空间使用复数. 最典型的例子有,在FCL中,我们需要把所有的非泛型集合类集中在一起存放,所以就有了 ...
- Win10 安装配置Android sdk及adb环境变量
今天在新买的win10系统笔记本上安装配置adb,开始觉得挺简单的事,公司win7电脑上有现成的,但实际过程中……没想的那么简单了!好了,废话少说,直接正题. 研究了好一会下,总算搞定,总结如下: 1 ...
- 自定义DropDownMenu菜单
在JayFang1993 / DropDownMenu的基础上进行修改,最后的到自己想要的效果 本来的效果: 而我最后实现的效果是: 我们先来分析一下DropDownMenu的源代码 需要改动的地方 ...
- Duplicate entry '127' for key 'PRIMARY'的解决方法
如果这个时候数据表里面没有数据,而且我们用使用 INSERT INTO VALUES 这样的语句插入,就会提示 Duplicate entry '127' for key 'PRIMARY'
- 文件查找记录类型 - TSearchRec - 文件操作(二)
SysUtils单元下的TSearchRec是一个记录类型,主要通过FindFirst, FindNext, and FindClose使用. 接上一篇举例说明TSearchRec常用成员 //sys ...
- 多线程“尚未调用coinitialize” 报错
关于多线程中创建使用TADOConnect.TADODataSet等Com组件时,必须先初始化Com 在多线程启用执行前 CoInitialize(nil); 在多线程启用执行后 CoUninitia ...
- python 爬虫登录保存会话去获取只有登录能获取的数据
#!/usr/bin/env python # -*- coding: utf-8 -*- # import ConfigParser import datetime import sys impor ...
- [LeetCode 题解]: Interger to Roman
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given an i ...
- selenium三大浏览器driver下载地址
Chrome 点击下载chrome的webdriver: http://chromedriver.storage.googleapis.com/index.html 不同的Chrome的版本对应的ch ...