Linq

Linq 是C# 3.0 新增的好东西,用来处理对象集合,可用来查询数据库,XML文档

主要分为    Linq To Objects (用来处理内存对象集合),也是本节的重点

               Linq TO  SQL

               Linq TO  XML

               Lnq  To  Providers

 

       1.  基本语法

            var   n=

                        from   数据源

                        where  ..

                        select   n;

 

           最后 foreach( var  a  in   n)  循环结果集,例子将展示最基本的用法.

 

            

namespace Linq_1 { class Program { static void Main(string[] args) { string[] strNames = { "小明","小李","小王","大胡","大大"}; var queryResults = from n in strNames where n.StartsWith("") select n; Console.WriteLine("名子以小开头的有: "); foreach (var item in queryResults) { Console.WriteLine(item); } Console.ReadKey(); } } }

 

声明字符串数组 strNames;  然后linq表达式  from 指定数据源,where 指明条件,select n 原则结果集

 

最后通过 foreach 获取结果集,延迟执行!将名字中以“小”开头的名字打印出来。

 

 

2. 用Linq方法语法和λ表达式(n=>xx)

             1) λ表达式

         n=>n<100    就是匿名函数,n为参数,n<100是函数或者方法体。若n<100则返回Ture

             2)Linq方法语法

                 同样例子查找以“小”开头的人名

 

                var  queryResult=strNames.where(n=>n.startwith("小"));

string[] args) { string[] strNames = { "小明", "小李", "小王", "大胡", "大大" }; var queryResults = strNames.Where(n => n.StartsWith("")); Console.WriteLine("名子以小开头的有: "); foreach (var item in queryResults) { Console.WriteLine(item); } Console.ReadKey(); }

 

 

                方法:OrderBy

foreach (var item in queryResults2) { Console.WriteLine(item); }

 

 

 

 

 

3. 合计运算符

Count(),Min(),Max(),Average(),Sum()

        

 

class Program { static void Main(string[] args) { int[] numbers = generateLotsOfNumbers(12345678); //小于1000的数字 var queryResults = from n in numbers where n < 1000 select n; Console.WriteLine("小于1000的数有:"); foreach (var str in queryResults) { Console.WriteLine(str); } //合计运算符操作 var queryResults2 = from n in numbers where n > 1000 select n; Console.WriteLine("Count of numbers >1000 "); Console.WriteLine(queryResults2.Count()); Console.WriteLine("min of numbers >1000"); Console.WriteLine(queryResults2.Min()); Console.WriteLine("max of numbers >1000"); Console.WriteLine(queryResults2.Max()); Console.WriteLine("average of numbers >1000"); Console.WriteLine(queryResults2.Average()); Console.WriteLine("sum of numbers >1000"); Console.WriteLine(queryResults2.Sum(n=>(long)n)); Console.ReadKey(); } /// <summary> /// 生成一个随机数列表 /// </summary> /// <param name="count"></param> /// <returns></returns> private static int[] generateLotsOfNumbers(int count) { Random generator = new Random(0); int[] result = new int[count]; for (int i = 0; i < count; i++) { result[i] = generator.Next(); } return result; } }

 

 

 

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Linq_查询复杂对象 { class Customer { public string ID { get; set; } public string City { get; set; } public string Country { get; set; } public string Region {get;set; } public decimal Sales{get;set;} public override string ToString() { return "ID: " + ID + " City" + City + " Country" + Country + " Region" + Region + " Sales" + Sales; } } class Program { static void Main(string[] args) { //查询asia亚洲 List<Customer> customers = new List<Customer> { new Customer{ID="A",City="New York",Country="USA",Region="North America",Sales=9999}, new Customer{ID="B",City="Mumbai",Country="India",Region="Asia",Sales=8888}, new Customer{ID="C",City="Karachi",Country="Pakistan",Region="Asia",Sales=7777}, }; var queryResults = from c in customers where c.Region == "Asia" select c; Console.WriteLine("Customers in Asia:"); foreach (var a in queryResults) { Console.WriteLine(a); } Console.ReadKey(); } } }

 


 

  
4. 投影:查询中创建对象

    select  n+1

    select  n.ToUpper()

    错误:select  n.name,n.city    只允许select one.所以当要查询多个数据时候应该创建对象

                                                         select   new {n.name,n.city}

 

 

 

           

 

 

 

using System; using System.Collections.Generic; using System.Linq; using System.Text; //投射.在查询中创建新对象 namespace Linq_投射.在查询中创建新对象 { class Customer { public string ID { get; set; } public string City { get; set; } public string Country { get; set; } public string Region { get; set; } public decimal Sales { get; set; } public override string ToString() { return "ID: " + ID + " City" + City + " Country" + Country + " Region" + Region + " Sales" + Sales; } } class Program { static void Main(string[] args) { //查询asia亚洲 List<Customer> customers = new List<Customer> { new Customer{ID="A",City="New York",Country="USA",Region="North America",Sales=9999}, new Customer{ID="B",City="Mumbai",Country="India",Region="Asia",Sales=8888}, new Customer{ID="C",City="Karachi",Country="Pakistan",Region="Asia",Sales=7777}, }; var queryResults = from c in customers where c.Region == "Asia" select new { c.City, c.Country, c.Sales }; //投射.在查询中创建新对象 var queryResults2 = customers.Where(c => c.Region == "Asia").Select(c => new { c.City, c.Country, c.Sales }); Console.WriteLine("Customers in Asia:"); foreach (var a in queryResults) { Console.WriteLine(a); } Console.WriteLine("Customers in Asia:"); foreach (var a in queryResults2) { Console.WriteLine(a); } Console.ReadKey(); } } }

 

 

 

5. 单值选项           select(n=>new {  xx}).Distinct();

 

6. Any()和All()       查找数据源是否有,有就Ture,否则false

          例:查找 是否有 集合项C的country 是否为 “USA”

 

             bool  anyUsa=Customers.Any(n=>n.country=="USA");

 

 

7. 多级排序        OrderBy(x).ThenBy(x)

using System; using System.Collections.Generic; using System.Linq; using System.Text; //orderby(c=>xx).ThenBy(c=>c.xx); // Take()类似SQL 的top,skip()跳过前几个结果; //First,firstorDefault() namespace Linq__多级排序 { class Customer { public string ID { get; set; } public string City { get; set; } public string Country { get; set; } public string Region { get; set; } public decimal Sales { get; set; } public override string ToString() { return "ID: " + ID + " City" + City + " Country" + Country + " Region" + Region + " Sales" + Sales; } } class Program { static void Main(string[] args) { //查询asia亚洲 List<Customer> customers = new List<Customer> { new Customer{ID="A",City="New York",Country="USA",Region="North America",Sales=9999}, new Customer{ID="B",City="Mumbai",Country="India",Region="Asia",Sales=8888}, new Customer{ID="C",City="Karachi",Country="Pakistan",Region="Asia",Sales=7777}, }; //普通排序 var queryResults = from c in customers orderby c.Country,c.ID,c.City select new { c.City, c.Country, c.Sales }; Console.WriteLine("Customers in Asia:"); foreach (var a in queryResults) { Console.WriteLine(a); } //多级排序方法 var queryResults2 = customers.OrderBy(c => c.Country).ThenBy(c => c.ID).ThenBy(c => c.Sales).Select(c => new { c.City, c.Country, c.Sales }); foreach (var a in queryResults2) { Console.WriteLine(a); } //Take() 取前1个结果 Console.WriteLine("queryResults2 的第一个结果是:"); foreach (var a in queryResults2.Take(1)) { Console.WriteLine(a); } //Skip(int) 排除前几个结果 Console.WriteLine("queryResults2 出去第一个结果是:"); foreach (var a in queryResults2.Skip(1)) { Console.WriteLine(a); } //First() Console.WriteLine("queryResults2 coutry是USA 的第一个结果是:"); Console.WriteLine(queryResults2.First(b=>b.Country=="USA")); Console.WriteLine("queryResults2 coutry是china 的第一个结果是:"); Console.WriteLine(queryResults2.FirstOrDefault(b => b.Country == "china")); Console.ReadKey(); } } }

 

 

 

8.  组合查询   

 

         from   c   in   xx

        group  c by c.Region  into cq

                    select   new {

                                       TotalPrice=cq.Sum(n=>c.sales),

                                        Region=cq.key

                                      }

 

 

9. Take()  类似 MSSQL 的Top(),返回前n个结果

    Skip() 跳过前n个结果集

 

foreach (var a in queryResults2.Take(1)) { Console.WriteLine(a); }

相关文章:

  • 2021-07-10
  • 2021-05-27
  • 2021-04-17
  • 2021-12-18
  • 2021-07-28
  • 2021-09-14
猜你喜欢
  • 2022-03-02
  • 2021-07-14
  • 2021-06-20
  • 2022-02-04
  • 2022-02-05
相关资源
相似解决方案