LINQ

LINQ:语言集成查询(Language Integrated Query),是一系列标准查询操作符的集合,这些操作符几乎对每一种数据源的导航,过滤和执行都是提供了底层的基本查询架构。
LINQ可查的数据源包括关系数据,XML,DataSet或内存中的数据.LINQ技术的重点是查询表达式,因为它描述了对数据源的具体操作。
Lambda 的一般规则如下:
Lambda 包含的参数数量必须与委托类型包含的参数数量相同。
Lambda 中的每个输入参数必须都能够隐式转换为其对应的委托参数。
Lambda 的返回值(如果有)必须能够隐式转换为委托的返回类型。
查询操作包含三部分:获取数据源,创建查询,执行查询
//获取数据源
            string[] Devices= {"电视" ,"电冰箱","洗衣机","电话","微波炉"};
            //创建查询
            var SelectDevices = from device in Devices
                                where device.StartsWith("电")
                                select device;
            //执行查询
            foreach (string dev in SelectDevices)
            {
                Console.WriteLine("带电的设备:{0}",dev);
            }

查询语法
      var SelectDevices = from device in Devices
                                where device.StartsWith("电")
                                select device;
方法语法
      var SelectDevices =Devices .Where ( device => device.StartsWith("电"))
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>)>) 并将结果序列合并为一个序列。
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 );
            }
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:按照一定的条件,将两个数据源关联起来
 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 ,mess=>mess. ID ,scos =>scos.ID ,(mes,sco)=>new {mes.ID, mes.Name, sco.ChineseScort, sco.MathsScort });  
        
GroupJoin:将主数据源中的每一个值或元素与次数据源中相应的值联接起来。
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) });
数据源1.GroupJoin(数据源2,变量1=>数据源1.关联字段,变量2=>数据源码2.关联字段,(数据源1数据变量,数据源2数据列表变量)=>new{变量a=数据源1.字段1,变量b=数据源1.字段2,变量c=数据源2列表变量.Select(变量c=变量c)})
5.分组操作符:按照一定的值将序列中的值或元素进行分组。
GroupBy: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));
7.聚合操作符:在一系列值上执行特定的运算,并返回单个值。
Aggregate:从序列或集合中收集值。   

            string[] citys = {"北京","上海","东京"};
            string newcity = citys.Aggregate((cityname,next)=>next+"-"+cityname);
            Console.WriteLine(newcity);
8.Average:求一个数值序列的平均值。   
         Demo1:
            double[] nums = {1.2,34.1,45.21,43.1 };
            Console.WriteLine(nums.Average ());
9.Count:求一个数值序列的个数。(LongCount用法相同)   
         Demo1:
            double[] nums = {1.2,34.1,45.21,43.1 };
            Console.WriteLine(nums.Count(num=>num<10));
10.Sum:求一个数值序列的和。   
         Demo1:
            double[] nums = {1.2,34.1,45.21,43.1 };
            Console.WriteLine(nums.Where (numm=>numm>10).Sum(num=>num));
11.集合操作符:对元素的集合或序列集合进行操作,并返回一个集合。
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);
            }
12.生成操作符:从现有的序列中创建新的序列。
 
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);
            }
13.转换操作符:将输入对象类型转变为序列的动作。
 
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);
                }
            }
14.元素操作符:从一个序列返回单个特定的元素。
 
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 ==1002).Select(lis=>lis.OrderNum).SingleOrDefault();          
            Console.WriteLine("订单号:{0}", value);
15.相等操作符:比较两个序列的元素是否相同。
 
SequenceEqual
           
    int[] Arr1 = { 1, 2, 3 };
            int[] Arr2 = { 1, 2, 3 };
            Console.WriteLine(Arr1.SequenceEqual(Arr2))
16.量词操作符:是否存在部分或全部元素符合某个特定条件。
 
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));
17.分割操作符:将一个序列分割成两个或多个序列。
 
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);
            }
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章