目录
一、Linq介绍
二、Linq语句
1、select
2、Where
3、Order
4、OfType
5、Join 、GroupJoin
6、Reverse
7、GroupBy
8、Any、All
9、Skip
10、Take、Count
11、Sum、Average、Max、Min
12、Concat、Distinct
13、ElementAt
14、First/Single、Last
15、ToDictionary、ToList
16、SequenceEqual
LINQ(Language-Integrated Query,语言集成查询)
四种关键技术:
select:返回指定类型
Where查询特点条件(方式1:from in;方式2:Lambda表达式):
List list = new List() { "111","222","33","44"};
var list2=from m in list where m.Length==3 select m;
var list3=list.Where(m => m.Length==2); //使用Lambda表达式
foreach (var m in list3)
Console.WriteLine(m);
Order排序:1、descending 降序;2、ascending 升序
List list = new List() { 11, 2, 23, 7 };
//var list2=from m in list orderby m descending select m;
var list2 = from m in list orderby m ascending select m;
//var list3 = list.OrderBy(x => x).ToList();//Lambda表达式
var list3 = list.OrderByDescending(x => x).ToList();
foreach (var m in list3)
Console.WriteLine(m);
OfType查询特定类型:
List
Join合并两集合通过指定键,返回指定结构类型集合
(GroupJoin:俩集合通过指定键分组)
List list3 = new List() { new Stu(1, "Tom"), new Stu(2, "Lisa"), new Stu(3, "Jake"), new Stu(4, "auston") };
List list4 = new List() { "Semi", "Lisa", "auston" };
var list5 = list3.Join(list4, p => p.Name, s => s, (p, s) => new { NewID = p.Id, NewName = s }).ToList();
foreach (var item in list5)
Console.WriteLine(item.NewName);
var list6 = list3.GroupJoin(list4, p => p.Name, s => s, (p, result) => new { plist = p.Name, count = result.Count() });
Reverse反转集合元素顺序
GroupBy按指定键对自身分组
var list7=list3.GroupBy(p=>p.Name,(name,p)=>new {Name=name,count=p.Count() });
foreach (var item in list7)
Console.WriteLine(item);
Any / All 判断是否(任意一个/全部)满足条件
bool isOk=list3.Any(p=>p.Score==100);
isOk=list3.All(p=>p.Score>10);
Console.WriteLine(isOk);
Skip跳过指定数量元素
var list8=list3.Skip(3).ToList();
Take拿取指定数量元素
Count获取元素个数
var list8=list3.Skip(3).Take(1);
Sum、Average、Max、Min获取集合总值、平均值、最大值、最小值
var total = list3.Where(p => p.Score > 60).Sum(p => p.Score);
var average=list3.Average(p => p.Score);
var Max=list3.Max(p => p.Score);
var Min = list3.Min(p => p.Score);
Concat连接集合
Distinct去重(去重类中某个字段需实现IEqualityComparer接口)
List list10 = new List() { 4,3,2};
List list11=new List() { 1,2,3};
var list12=list10.Concat(list11).Distinct();
var list13=list3.Distinct(new Stu());//Stu类实现IEqualityComparer接口
class Stu : IEqualityComparer
{
public int Score { get; set; }
public string Name { get; set; }
public bool Equals(Stu? x, Stu? y)
{
if (x.Name == null || y.Name == null)
return false;
if (x.Name == y.Name) return true;
return false;
}
public int GetHashCode([DisallowNull] Stu obj)
{
return obj.GetHashCode();
}
}
ElementAt获取指定索引元素(与[ ]类似)
var stu=list3.ElementAt(3);
First/Single、Last:获取集合中第一个、最后一个元素(如果集合中包含多个元素,使用Single会报错);
ToDictionary:将集合转换为字典;
ToList: 将集合转换为List;
SequenceEqual:判断两个集合是否相等;