LINQ标准查询操作符
1.投影操作符:将序列中的元素转换为一个由开发人员定义的形式的操作。
- Select :对单个序列或集合中的值进行投影。
string[] Devices = { "电视", "电冰箱", "洗衣机", "电话", "微波炉" };
var SelectDevices1 = from device in Devices
select device;
// var SelectDevices = Devices.Select(device=>device);
foreach (string dev in SelectDevices1)
{
Console.WriteLine("带电的设备:{0}", dev);
}
- SelectMany:将序列的每个元素投影到 IEnumerable<(Of <(T>)>) 并将结果序列合并为一个序列。
- SelectMany:将序列的每个元素投影到 IEnumerable<(Of <(T>)>) 并将结果序列合并为一个序列。
class Devices
{
public string Name
{ get; set; }
public List<double> Price
{ get; set; }
}
static void Main()
{
Devices[] DeviceGroup = { new Devices { Name = "电视", Price =new List<double>{ 3000,2000} }, new Devices { Name = "电冰箱", Price =new List<double> { 4000,5000 }}, new Devices { Name = "洗衣机", Price =new List<double> { 1500,1000 }} };
var devices = DeviceGroup.SelectMany(device => device.Price );
foreach (var v in devices)
{
Console.WriteLine(v);
}
}
2.限制操作符:按照一定的限制,对序列进行过滤。
- Where:对单个序列或集合中的值进行投影。
string[] Devices = { "电视", "电冰箱", "洗衣机", "电话", "微波炉" };
var SelectDevices = from device in Devices
where device.StartsWith("电")
select device;
//var SelectDevices = Devices.Where(device=>device.StartsWith ("电"));
foreach (string dev in SelectDevices)
{
Console.WriteLine("带电的设备:{0}", dev);
}
3.排序操作符:按照升序和降序的方式对结果进行排序的功能。
- OrderBy:将序列中的返回值按照升序的顺序进行排列。
string[] Devices = { "电视", "电冰箱", "洗衣机", "电话", "微波炉" };
var SelectDevices = from device in Devices
orderby device
select device;
// var SelectDevices = Devices.OrderBy (device => device);
foreach (string dev in SelectDevices)
{
Console.WriteLine("带电的设备:{0}", dev);
}
- OrderByDescending:将序列中的返回值按照降序的顺序进行排列。
string[] Devices = { "电视", "电冰箱", "洗衣机", "电话", "微波炉" };
var SelectDevices = from device in Devices
orderby device descending
select device;
// var SelectDevices = Devices.OrderByDescending(device => device);
foreach (string dev in SelectDevices)
{
Console.WriteLine("带电的设备:{0}", dev);
}
- ThenBy:排序依据的次关键字。
Devices[] DeviceGroup = { new Devices { Name = "电视", Price = 10000 }, new Devices { Name = "电话", Price = 240 }, new Devices { Name = "电视", Price = 3000 } };
var devices = from device in DeviceGroup
orderby device.Name,device .Price
select device;
// var devices = DeviceGroup.AsQueryable().OrderBy(device => device.Name).ThenBy(device => device.Price);
foreach (var dev in devices)
{
Console.WriteLine("品名:{0},价格:{1}",dev.Name,dev.Price );
}
- ThenByDescending:倒排序依据的次关键字。
Devices[] DeviceGroup = { new Devices { Name = "电视", Price = 10000 }, new Devices { Name = "电话", Price = 240 }, new Devices { Name = "电视", Price = 3000 } };
var devices = from device in DeviceGroup
orderby device.Name,device .Price descending
select device;
// var devices = DeviceGroup.AsQueryable().OrderBy(device => device.Name).ThenByDescending(device => device.Price);
foreach (var dev in devices)
{
Console.WriteLine("品名:{0},价格:{1}",dev.Name,dev.Price );
}
- ThenByDescending:倒排序依据的次关键字。
Devices[] DeviceGroup = { new Devices { Name = "电视", Price = 10000 }, new Devices { Name = "电话", Price = 240 }, new Devices { Name = "电视", Price = 3000 } };
var devices = from device in DeviceGroup
orderby device.Name,device .Price descending
select device;
// var devices = DeviceGroup.AsQueryable().OrderBy(device => device.Name).ThenByDescending(device => device.Price);
foreach (var dev in devices)
{
Console.WriteLine("品名:{0},价格:{1}",dev.Name,dev.Price );
}
- Reverse:反转序列。
string[] Devices = { "电视", "电冰箱", "洗衣机", "电话", "微波炉" };
var SelectDevices = from device in Devices.Reverse()
select device;
//var SelectDevices = Devices.Select(device=>device).Reverse ();
foreach (string dev in SelectDevices)
{
Console.WriteLine("带电的设备:{0}", dev);
}
4.联接操作符:将两个或多个数据源对象进行关联或联合。
- Join:按照一定的条件,将两个数据源关联起来。
static void Main()
{
List<StudentMessage> A_Class = new List<StudentMessage>(); //声名一个A班,来存放学员
A_Class.Add(new StudentMessage { ID = 1001, Name = "张三", Sex = true, Age = 20 }); //添加学员
A_Class.Add(new StudentMessage { ID = 1002, Name = "李四", Sex = false, Age = 21 });//添加学员
A_Class.Add(new StudentMessage { ID = 1003, Name = "王五", Sex = true, Age = 19 }); //添加学员
List<StudentScort> A_ScortSheet = new List<StudentScort>(); //声名一个成绩表
A_ScortSheet.Add(new StudentScort { ID = 1001, ChineseScort = 90f, MathsScort = 88f }); //添加学员成绩
A_ScortSheet.Add(new StudentScort { ID = 1002, ChineseScort = 80f, MathsScort = 68f }); //添加学员成绩
A_ScortSheet.Add(new StudentScort { ID = 1003, ChineseScort = 60f, MathsScort = 98f }); //添加学员成绩
var messages = from mes in A_Class
join sco in A_ScortSheet on mes.ID equals sco.ID
select new { mes.ID, mes.Name, sco.ChineseScort, sco.MathsScort };
//var messages=A_Class.Join (A_ScortSheet ,mes=>mes .ID ,sco=>sco.ID ,(mes,sco)=>new {mes.ID, mes.Name, sco.ChineseScort, sco.MathsScort });
Console.WriteLine("{0,4} {1,10} {2,3} {3,3}", "学号","姓名","语文","数学");
foreach (var scort in messages)
{
Console.WriteLine("{0,6} {1,10} {2,4} {3,4}",scort .ID ,scort .Name ,scort.ChineseScort ,scort .MathsScort );
}
}
- GroupJoin:将主数据源中的每一个值或元素与次数据源中相应的值联接起来。
static void Main()
{
List<StudentMessage> A_Class = new List<StudentMessage>(); //声名一个A班,来存放学员
A_Class.Add(new StudentMessage { ID = 1001, Name = "张三", Sex = true, Age = 20 }); //添加学员
A_Class.Add(new StudentMessage { ID = 1002, Name = “李四”, Sex = false, Age = 21 });//添加学员
List<Scort> A_ScortSheet = new List<Scort>(); //声名一个成绩表
A_ScortSheet.Add(new ChineaseScort { ID = 1001, Scort = 100f, Subject = "语文" }); //添加语文成绩
A_ScortSheet.Add(new ChineaseScort { ID = 1002, Scort = 80f, Subject = “语文” }); //添加语文成绩
A_ScortSheet.Add(new MathsScort { ID = 1001, Scort = 90f, Subject = “数学” }); //添加数学成绩
A_ScortSheet.Add(new MathsScort { ID = 1002, Scort = 60f, Subject = “数学” }); //添加数学成绩
var messages = A_Class.GroupJoin(A_ScortSheet, mes => mes.ID, sco => sco.ID, (mess, scor) => new { Mess = mess.ID, Mename = mess.Name, Scor = scor.Select(Scor => Scor) });
foreach (var scort in messages)
{
Console.WriteLine("学号:{0,4} 姓名:{1}", scort.Mess, scort.Mename);
foreach (var sc in scort.Scor)
{
Console.WriteLine(" {0}:{1}分", sc.Subject, sc.Scort);
}
}
数据源1.GroupJoin(数据源2,变量1=>数据源1.关联字段,变量2=>数据源码2.关联字段,(数据源1数据变量,数据源2数据列表变量)=>new{变量a=数据源1.字段1,变量b=数据源1.字段2,变量c=数据源2列表变量.Select(变量c=变量c)})
5.分组操作符:按照一定的值将序列中的值或元素进行分组。
- GroupBy:将序列中的返回值按照升序的顺序进行排列。
class Student
{
public string ClassName
{ get; set; }
public string Name
{ get; set; }
}
static void Main()
{
Student[] students = new Student[] {
new Student{ClassName="A", Name="张三"},
new Student{ClassName ="B", Name ="李四"},
new Student{ClassName ="A" ,Name ="王五"},
new Student {ClassName ="B", Name ="赵六"},
new Student{ClassName ="B" ,Name ="钱七"},
new Student {ClassName ="B", Name ="孙八"}
};
var stus = (from stu in students
select stu).GroupBy(st => st.ClassName);
//var stus = students.GroupBy(st => st.ClassName);
foreach (var v in stus)
{
Console.WriteLine("{0}班学生:", v.Key);
foreach (var va in v)
{
Console.WriteLine(" 姓名:{0}", va.Name);
}
}
}
6.合并操作符:将两个对象合并在一起。
- Concat:
string[] Citys = new string[] { "北京","上海","东京"};
string[] Mobiles = new string[] {"诺基亚","摩托罗拉","三星" };
var Cont = Citys.Select(city => city).Concat(Mobiles.Select(mobil => mobil));
foreach (var v in Cont)
{
Console.WriteLine(v);
}
7.聚合操作符:在一系列值上执行特定的运算,并返回单个值。
- Aggregate:从序列或集合中收集值。
string[] citys = {"北京","上海","东京"};
string newcity = citys.Aggregate((cityname,next)=>next+"-"+cityname);
Console.WriteLine(newcity);
- Average:求一个数值序列的平均值。
Demo1:
double[] nums = {1.2,34.1,45.21,43.1 };
Console.WriteLine(nums.Average ());
Demo2:
List<StudentSoc> list = new List<StudentSoc>();
list.Add(new StudentSoc { Name = "张三", Chinese = 90f });
list.Add(new StudentSoc { Name = "李四", Chinese = 94f });
list.Add(new StudentSoc { Name = "王五", Chinese = 92f });
list.Add(new StudentSoc { Name = "赵六", Chinese = 78f });
var quer = from stu in list select stu.Chinese;
Console.WriteLine(quer .Average ());
//var quer = list.Average(lis=>lis.Chinese );
//Console.WriteLine(quer);
- Count:求一个数值序列的个数。(LongCount用法相同)
Demo1:
double[] nums = {1.2,34.1,45.21,43.1 };
Console.WriteLine(nums.Count(num=>num<10));
Demo2:
List<StudentSoc> list = new List<StudentSoc>();
list.Add(new StudentSoc { Name = "张三", Chinese = 90f });
list.Add(new StudentSoc { Name = "李四", Chinese = 94f });
list.Add(new StudentSoc { Name = "王五", Chinese = 92f });
list.Add(new StudentSoc { Name = "赵六", Chinese = 78f });
var quer = from stu in list
where stu.Chinese >80
select stu.Chinese;
Console.WriteLine(quer.Count());
//var quer = list.Count(lis=>lis.Chinese >80);
//Console.WriteLine(quer);
- Sum:求一个数值序列的和。
Demo1:
double[] nums = {1.2,34.1,45.21,43.1 };
Console.WriteLine(nums.Where (numm=>numm>10).Sum(num=>num));
Demo2:
List<StudentSoc> list = new List<StudentSoc>();
list.Add(new StudentSoc { Name = "张三", Chinese = 90f });
list.Add(new StudentSoc { Name = "李四", Chinese = 94f });
list.Add(new StudentSoc { Name = "王五", Chinese = 92f });
list.Add(new StudentSoc { Name = "赵六", Chinese = 78f });
var quer = from stu in list
where stu.Chinese < 93
select stu.Chinese;
Console.WriteLine(quer.Sum());
//var quer = list.Where(liss => liss.Chinese < 93).Sum(lis => lis.Chinese);
// Console.WriteLine(quer);
8.集合操作符:对元素的集合或序列集合进行操作,并近观回一个集合。
- Distinct:删除集合中重复的值,并返回该项集合中互不相同的元素。
List<StudentSoc> list = new List<StudentSoc>();
list.Add(new StudentSoc { Name = "李四", Chinese = 94f });
list.Add(new StudentSoc { Name = "李四", Chinese = 94f });
list.Add(new StudentSoc { Name = "王五", Chinese = 92f });
StudentSoc s = new StudentSoc { Name = "赵六", Chinese = 78f };
list.Add(s);
list.Add(s);
//var quer = from stu in list
// select stu;
//foreach (var que in quer.Distinct())
//{
// Console.WriteLine(que.Name +":"+que.Chinese );
//}
var quer = list.Distinct();
foreach (var que in quer)
{
Console.WriteLine(que.Name + ":" + que.Chinese);
}
- Union:将两个集合或序列合并后返回不同的元素。
int[] nums1 = {1,2,3,3,4};
int[] nums2 = { 2, 3, 4, 5, 6 };
var newnums = nums1.Union(nums2);
foreach (var num in newnums)
{
Console.WriteLine(num);
}
- Intersect:返回两个集合的交集。
int[] nums1 = {1,2,3,3,4};
int[] nums2 = { 2, 3, 4, 5, 6 };
var newnums = nums1.Intersect(nums2);
foreach (var num in newnums)
{
Console.WriteLine(num);
}
- Except:返回序列一中序列二没有的值。
int[] nums1 = {1,2,3,3,4,7};
int[] nums2 = { 2, 3, 4, 5, 6 ,9,23};
var newnums = nums1.Except(nums2);
foreach (var num in newnums)
{
Console.WriteLine(num);
}
9.生成操作符:从现有的序列中创建新的序列。
- Empty:指定类型的空集。
var s= Enumerable.Empty<string>();
Console.WriteLine(s.Count ());
- Range:创建一个包含数字序列的集合。
foreach (var num in Enumerable.Range(3, 9))
{
Console.WriteLine(num);
}
- Repeat:将值重复一定的次数。
foreach (var num in Enumerable.Repeat(“*****”,9))
{
Console.WriteLine(num);
}
10.转换操作符:将输入对象类型转变为序列的动作。
- AsEnumerable:
int[] ArrInt = {1,2,3,4,5 };
foreach (int i in ArrInt .Where (arr=>arr>1))
{
Console.WriteLine(i);
}
foreach (int i in ArrInt.AsEnumerable().Where(arr => arr > 1))
{
Console.WriteLine(i);
}
- Cast:将序列转换成指定的类型。
直接对Array应用Select是不可以的。
ArrayList AL = new ArrayList();
AL.Add(1);
AL.Add(2);
AL.Add(3);
AL.Add(4);
IEnumerable <int> que=AL.Cast<int>().Select (arr=>arr);
foreach (int i in que)
{
Console.WriteLine(i);
}
- OfType:过滤序列中的某种类型。
ArrayList AL = new ArrayList();
AL.Add(1);
AL.Add(2);
AL.Add("3");
AL.Add(4);
var que = AL.OfType<int>();
foreach (var i in que)
{
Console.WriteLine(i);
}
- ToArray:从Ienumerable序列创建一个数组。
List<StudentSoc> list = new List<StudentSoc>();
list.Add(new StudentSoc { Name = "张三", Chinese = 90f });
list.Add(new StudentSoc { Name = "李四", Chinese = 94f });
list.Add(new StudentSoc { Name = "王五", Chinese = 92f });
list.Add(new StudentSoc { Name = "赵六", Chinese = 78f });
var stu1 = list.Select(stud => stud.Chinese);
var stu = list.Select(stud => stud.Chinese).ToArray();
- ToDictionary:从Ienumerable序列创建一个Dictionary序列。
class StudentSoc
{
public string Name
{ get; set; }
public float Chinese
{ get; set; }
}
List<StudentSoc> list = new List<StudentSoc>();
list.Add(new StudentSoc { Name = "张三", Chinese = 90f });
list.Add(new StudentSoc { Name = "李四", Chinese = 94f });
list.Add(new StudentSoc { Name = "王五", Chinese = 92f });
list.Add(new StudentSoc { Name = "赵六", Chinese = 78f });
Dictionary<float ,StudentSoc> stu = list.ToDictionary(stud => stud.Chinese );
foreach (KeyValuePair<float,StudentSoc > item in stu)
{
Console.WriteLine(item.Key +" "+item.Value.Name +" "+item.Value .Chinese );
}
- ToList:从Ienumerable序列创建一个List序列。
class StudentSoc
{
public string Name
{ get; set; }
public float Chinese
{ get; set; }
}
List<StudentSoc> list = new List<StudentSoc>();
list.Add(new StudentSoc { Name = "张三", Chinese = 90f });
list.Add(new StudentSoc { Name = "李四", Chinese = 94f });
list.Add(new StudentSoc { Name = "王五", Chinese = 92f });
list.Add(new StudentSoc { Name = "赵六", Chinese = 78f });
var stu = list.Select(lis=>lis.Chinese).ToList();
foreach (var item in stu)
{
Console.WriteLine(item );
}
- ToLookup:从Ienumerable序列创建一个 Lookup序列。Lookup是主键的集合,其中主键对应着一个或多个值。
class OrderTable
{
public int OrderNum
{ get; set; }
public double Amount
{ get; set; }
}
List<OrderTable> list = new List<OrderTable>();
list.Add(new OrderTable { OrderNum = 1001, Amount = 1234.5 });
list.Add(new OrderTable { OrderNum = 1002, Amount = 2340 });
list.Add(new OrderTable { OrderNum = 1001, Amount = 3000 });
var lis = list.ToLookup(num => num.OrderNum, num => num.Amount);
foreach (var item in lis)
{
Console.WriteLine("订单号:{0}",item.Key );
foreach (var v in item)
{
Console.WriteLine(" {0}元",v);
}
}
11.元素操作符:从一个序列返回单个特定的元素。
- DefaultIfEmpty:将空集合替换为包含默认的单个值的集合。
List<OrderTable> list = new List<OrderTable>();
list.Add(new OrderTable { OrderNum = 1001, Amount = 1234.5 });
list.Add(new OrderTable { OrderNum = 1002, Amount = 2340 });
list.Add(new OrderTable { OrderNum = 1001, Amount = 3000 });
var lis = list.Where(num => num.OrderNum == 1001);
foreach (var item in lis.DefaultIfEmpty(new OrderTable { OrderNum =0,Amount =0}))
{
Console.WriteLine("订单号:{0}", item.Amount);
}
- ElementAt:返回集合中给定索引的元素。
List<OrderTable> list = new List<OrderTable>();
list.Add(new OrderTable { OrderNum = 1001, Amount = 1234.5 });
list.Add(new OrderTable { OrderNum = 1002, Amount = 2340 });
list.Add(new OrderTable { OrderNum = 1001, Amount = 3000 });
var value = list.Where(num => num.OrderNum == 1001).ElementAt (1);
Console.WriteLine("订单号:{0}", value.Amount );
- ElementAtOrDefault:是将ElementAt和DefaultIfEmpty。
List<OrderTable> list = new List<OrderTable>();
list.Add(new OrderTable { OrderNum = 1001, Amount = 1234.5 });
list.Add(new OrderTable { OrderNum = 1002, Amount = 2340 });
list.Add(new OrderTable { OrderNum = 1001, Amount = 3000 });
var value = list.Select (lis=>lis.OrderNum).ElementAtOrDefault(3);
Console.WriteLine("订单号:{0}", value);
- First:返回集合中的第一个元素(Last返回最后一个)。
List<OrderTable> list = new List<OrderTable>();
list.Add(new OrderTable { OrderNum = 1001, Amount = 1234.5 });
list.Add(new OrderTable { OrderNum = 1002, Amount = 2340 });
list.Add(new OrderTable { OrderNum = 1001, Amount = 3000 });
var value = list.Select (lis=>lis.OrderNum).First ();
Console.WriteLine("订单号:{0}", value);
- FirstOrDefault:返回集合中的第一个元素,如果不存在,返回默认值(LastOrDefault返回最后一个,如果不存在,返回默认值)。
List<OrderTable> list = new List<OrderTable>();
list.Add(new OrderTable { OrderNum = 1001, Amount = 1234.5 });
list.Add(new OrderTable { OrderNum = 1002, Amount = 2340 });
list.Add(new OrderTable { OrderNum = 1001, Amount = 3000 });
var value = list.Where (li=>li.OrderNum ==1003).Select(lis=>lis.OrderNum).FirstOrDefault();
Console.WriteLine("订单号:{0}", value);
- Single:从一个序列中返回单个元素,或唯一满足某一特定条件的元素。(LastOrDefault返回最后一个,如果不存在,返回默认值)。
List<OrderTable> list = new List<OrderTable>();
list.Add(new OrderTable { OrderNum = 1001, Amount = 1234.5 });
list.Add(new OrderTable { OrderNum = 1002, Amount = 2340 });
list.Add(new OrderTable { OrderNum = 1001, Amount = 3000 });
var value = list.Where (li=>li.OrderNum ==1002).Select(lis=>lis.OrderNum).Single();
Console.WriteLine("订单号:{0}", value);
- SingleOrDefault:从一个序列中返回单个元素,或唯一满足某一特定条件的元素。如果存在多条记录,抛出异常。
List<OrderTable> list = new List<OrderTable>();
list.Add(new OrderTable { OrderNum = 1001, Amount = 1234.5 });
list.Add(new OrderTable { OrderNum = 1002, Amount = 2340 });
list.Add(new OrderTable { OrderNum = 1001, Amount = 3000 });
var value = list.Where (li=>li.OrderNum ==1001).Select(lis=>lis.OrderNum).SingleOrDefault();
Console.WriteLine("订单号:{0}", value);
12.相等操作符:比较两个序列的元素是否相同。
- SequenceEqual
int[] Arr1 = { 1, 2, 3 };
int[] Arr2 = { 1, 2, 3 };
Console.WriteLine(Arr1.SequenceEqual(Arr2))
13.量词操作符:是否存在部分或全部元素符合某个特定条件。
- All:判定在集合中是否所有的值都满足特定的条件。
int[] Arr1 = { 1, 1, 1 };
Console.WriteLine(Arr1.All (arr=>arr==1));
- Any:判定在集合中是否有的值满足特定的条件。
int[] Arr1 = { 1, 2, 3 };
Console.WriteLine(Arr1.Any (arr=>arr==1));
- Contains:判定在集合中是否包含某个值。
int[] Arr1 = { 1, 2, 3 };
Console.WriteLine(Arr1.Contains(4));
14.分割操作符:将一个序列分割成两个或多个序列。
- Skip:跳过序列的前n个元素后返回所有的元素。
int[] Arr = { 1, 2, 3,4,5,6 };
foreach (int i in Arr.Skip(2))
{
Console.WriteLine(i);
}
- SkipWhile:跳过不满足条件的元素,返回余下元素的序列。
需要注意的是,这种跳出过必需排序后才能合部跳过满足条件的元素。
int[] Arr = { 1, 12, 3,4,15,6};
foreach (int i in Arr.OrderBy (nu=>nu).SkipWhile(arr=>arr<=10))
{
Console.WriteLine(i);
}
- Take:返回序列的从开始到参数指定位置的元素。
int[] Arr = { 1, 2, 3,4,5,6 };
foreach (int i in Arr.Take(2))
{
Console.WriteLine(i);
}
- TakeWhile:返回满足条件的元素。
需要注意的是,这种返回必需排序后才能进行操作。
int[] Arr = { 1, 12, 3,4,15,6};
foreach (int i in Arr.OrderBy (ar=>ar).TakeWhile(arr=>arr<12))
{
Console.WriteLine(i);
}
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524