core的 Linq基本使用,简单模拟数据库多表的左右内连接的测试
1:先看效果:
2:部分代码截图
3:全部代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 namespace Redistest02 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 //Console.WriteLine("Hello DoSubscriberAsync!"); 11 //MyRedisHelper.DoSubscriberAsync("myredis").Wait(30); 12 //Console.ReadLine(); 13 14 //==================准备模拟两张表的数据 15 var list01 = new List<Student>();//3条数据 16 Enumerable.Range(1, 3).ToList().ForEach(c => 17 { 18 list01.Add(new Student { id = 11 + c, Name = "qq" + c }); 19 }); 20 21 var list02 = new List<Student>();//两条数据 22 list02.Add(new Student { id = 12, Name = "qq1" }); 23 list02.Add(new Student { id = 13, Name = "qq2" }); 24 25 Console.WriteLine("==========左连接==以左边为准============="); 26 //左连接 27 var newlistL = (from q in list01 28 join a in list02 29 on q.id equals a.id into qa 30 from c in qa.DefaultIfEmpty() 31 select new Student 32 { 33 id = c == null ? 0 : c.id, 34 Name = c == null ? "空的" : c.Name 35 }).ToList(); 36 newlistL.ForEach(c => Console.WriteLine($"id={c.id},name={c.Name}")); 37 38 //右连接 39 Console.WriteLine("==========右连接===以右边为准============"); 40 var newlistR = (from a in list02 41 join q in list01 42 on a.id equals q.id into qa 43 from c in qa.DefaultIfEmpty() 44 select new Student 45 { 46 id = c == null ? 0 : c.id, 47 Name = c == null ? "空的" : c.Name 48 }).ToList(); 49 newlistR.ForEach(c => Console.WriteLine($"id={c.id},name={c.Name}")); 50 51 //内连接 52 Console.WriteLine("==========内连接======两边共同的数据========="); 53 var newlistI = (from a in list02 54 join q in list01 55 on a.id equals q.id 56 select new Student 57 { 58 id = q == null ? 0 : q.id, 59 Name = q == null ? "空的" : q.Name 60 61 }).ToList(); 62 newlistI.ForEach(c => Console.WriteLine($"id={c.id},name={c.Name}")); 63 64 65 Enumerable.Range(1, 10).ToList().ForEach(c => 66 { 67 Console.WriteLine(c); 68 }); 69 var listdata = Enumerable.Empty<Student>(); 70 Console.WriteLine($"listdata的集合对象数据是:{listdata.Count()}个,null就会报错的!"); 71 } 72 } 73 74 public class Student 75 { 76 public int id { get; set; } 77 public string Name { get; set; } 78 // public DateTime Birthday { get; set; } 79 80 //public IEnumerable<Student> GetSpectionMenthod 81 //{ 82 // get 83 // { 84 // // yield return Enumerable.Empty<Student>().FirstOrDefault(); 85 // yield return new Student { }; 86 // } 87 } 88 89 }
怎么样,看了之后还是很简单的对吧,嘻嘻!
如有疑问或者错误的地方,请跟帖,本人会第一时间答复以及相互学习,谢谢!个人会不断的上传自己的学习心得!
好了今天就先到这里,下次有时间再更新,如果存在不合理的地方,欢迎大家多多指教留言!!!