看代码实现:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Test 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 List<Test> listData = new List<Test>{ 14 new Test { Name = "jiangjing", Age = 18, Sex = "boy"}, 15 new Test { Name = "wenting", Age = 17, Sex = "girl"}, 16 new Test { Name = "caihong", Age = 80, Sex = "boy"}, 17 new Test { Name = "caiyun", Age = 90, Sex = "boy"} 18 }; 19 20 //string[] names = {"jiangjing", "wenting", "caihong", "test"}; 21 //1.使用查询方式 22 //var res = from n in names 23 // where n.EndsWith("g") 24 // orderby n.Substring(n.Length-1) 25 // select n; 26 27 //2.使用方法方式 28 //var res = names.OrderBy(n=>n).Where(n=>n.EndsWith("g")); 29 //foreach (var name in res) 30 // Console.WriteLine(name); 31 32 //3.聚合函数的相关使用,分析大型数据结果 33 //var resultData = listData.Where(t=>t.Age<20).Select(t=>t.Age); 34 35 //4.投影:在查询中新建对象 36 //var resultData = listData.Where(t => t.Sex == "boy").Select(t => new { Name = t.Name, Age = t.Age }); 37 //foreach (var item in resultData) 38 // Console.WriteLine(item); 39 40 //5.单值选择:Distinct()函数 41 //var resultData = listData.Where(t => t.Sex == "boy").Select(t => new { Name = t.Name, Age = t.Age }).Distinct(); 42 //foreach (var item in resultData) 43 // Console.WriteLine(item); 44 45 //6.Any和All方法 46 //bool falg1 = resultData.Any(t=>t.Name=="jiangjing"); 47 //bool falg2 = resultData.All(t => t.Name == "jiangjing"); 48 //Console.Write("{0} {1}", falg1, falg2); 49 50 //7.多级排序,使用方法也行orderby,thenby...,不过写起来还没这个清晰 51 //var resultData = from t in listData 52 // orderby t.Age, t.Name 53 // select new { Name = t.Name, Age = t.Age}; 54 //foreach (var item in resultData) 55 // Console.WriteLine(item); 56 57 //8.组合查询 58 //var resultData = from t in listData 59 // group t by t.Sex into tg 60 // select new { SumAge = tg.Sum(t => t.Age), Sex = tg.Key }; 61 62 //foreach (var item in resultData) 63 // Console.WriteLine(item); 64 65 //9.查询结果使用take函数或者skip函数 66 67 //var resultData = listData.Where(t=>t.Age<20); 68 69 //foreach (var item in resultData.Take(1))//take函数是取结果集的前n个 70 // Console.WriteLine(item); 71 72 //foreach (var item in resultData.Skip(1))//skip函数则是跳过结果集的前n个 73 // Console.WriteLine(item); 74 75 Console.ReadKey(); 76 } 77 } 78 79 class Test 80 { 81 public string Name { get; set; } 82 public int Age { get; set; } 83 84 public string Sex { get; set; } 85 86 public override string ToString() 87 { 88 return "名字:" + Name + "\n" + "年龄:" + Age; 89 } 90 } 91 }
时间: 2025-01-15 02:02:06