您的位置:首页 > 数据库

core的 Linq基本使用,简单模拟数据库多表的左右内连接的测试

2020-08-21 20:56 906 查看

1:先看效果:

using System;
using System.Collections.Generic;
using System.Linq;
namespace Redistest02
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello DoSubscriberAsync!");
//MyRedisHelper.DoSubscriberAsync("myredis").Wait(30);
//Console.ReadLine();

//==================准备模拟两张表的数据
var list01 = new List<Student>();//3条数据
Enumerable.Range(1, 3).ToList().ForEach(c =>
{
list01.Add(new Student { id = 11 + c, Name = "qq" + c });
});

var list02 = new List<Student>();//两条数据
list02.Add(new Student { id = 12, Name = "qq1" });
list02.Add(new Student { id = 13, Name = "qq2" });

Console.WriteLine("==========左连接==以左边为准=============");
//左连接
var newlistL = (from q in list01
join a in list02
on q.id equals a.id into qa
from c in qa.DefaultIfEmpty()
select new Student
{
id = c == null ? 0 : c.id,
Name = c == null ? "空的" : c.Name
}).ToList();
newlistL.ForEach(c => Console.WriteLine($"id={c.id},name={c.Name}"));

//右连接
Console.WriteLine("==========右连接===以右边为准============");
var newlistR = (from a in list02
join q in list01
on a.id equals q.id into qa
from c in qa.DefaultIfEmpty()
select new Student
{
id = c == null ? 0 : c.id,
Name = c == null ? "空的" : c.Name
}).ToList();
newlistR.ForEach(c => Console.WriteLine($"id={c.id},name={c.Name}"));

//内连接
Console.WriteLine("==========内连接======两边共同的数据=========");
var newlistI = (from a in list02
join q in list01
on a.id equals q.id
select new Student
{
id = q == null ? 0 : q.id,
Name = q == null ? "空的" : q.Name

}).ToList();
newlistI.ForEach(c => Console.WriteLine($"id={c.id},name={c.Name}"));

Enumerable.Range(1, 10).ToList().ForEach(c =>
{
Console.WriteLine(c);
});
var listdata = Enumerable.Empty<Student>();
Console.WriteLine($"listdata的集合对象数据是:{listdata.Count()}个,null就会报错的!");
}
}

public class Student
{
public int id { get; set; }
public string Name { get; set; }
// public DateTime Birthday { get; set; }

//public IEnumerable<Student> GetSpectionMenthod
//{
//    get
//    {
//        //  yield return Enumerable.Empty<Student>().FirstOrDefault();
//        yield return new Student { };
//    }
}

}
View Code 怎么样,看了之后还是很简单的对吧,嘻嘻!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: