C# LINQ中Join与GroupJoin的区别
新建控制台项目ConsoleDemo,添加Testlinq类,代码如下:
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace ConsoleDemo { public class Testlinq { private List<UserDepart> userDeparts = new List<UserDepart> { }; private List<NoticeData> noticeDatas = new List<NoticeData> { }; public Testlinq() { for (int i = 0; i < 10; i++) { userDeparts.Add(new UserDepart { UserId = i + 1, Name = $"机构:{i + 1}", DepartmentId = i + 1 }); if (i % 2 == 0) { noticeDatas.Add(new NoticeData { Id = i + 1, Name = $"公告:{i + 1}", DepartmentId = i + 1 }); } } } public void Testjoin() { //查询语法 var x = from a in userDeparts join b in noticeDatas on a.DepartmentId equals b.DepartmentId select new { name = a.Name, id = a.DepartmentId }; Console.WriteLine("输出连接信息如下:"); foreach (var item in x) { Console.WriteLine($"{item.name},{item.id}"); } //函数语法 //var s = userDeparts.Join(noticeDatas, a => a.DepartmentId, b => b.DepartmentId, (a, b) => new { name = a.Name, id = a.DepartmentId }); //Console.WriteLine("输出连接信息如下:"); //foreach (var item in s) //{ // Console.WriteLine($"{item.name},{item.id}"); //} } public void TestGroupjoin() { //查询语法 var y = from a in userDeparts join b in noticeDatas on a.DepartmentId equals b.DepartmentId into clist select new { name = a.Name, list = clist }; Console.WriteLine("输出连接信息如下:"); foreach (var item in y) { Console.Write($"{item.name},内容如下:"); foreach (var subitem in item.list) { Console.Write($"{subitem.Name},{subitem.DepartmentId}"); } Console.WriteLine(); } //函数语法 var s = this.userDeparts.GroupJoin(noticeDatas, a => a.DepartmentId, b => b.DepartmentId, (a, blist) => new { name = a.Name, list = blist }); //Console.WriteLine("输出连接信息如下:"); //foreach (var item in s) //{ // Console.Write($"{item.name},内容如下:"); // foreach (var subitem in item.list) // { // Console.Write($"{subitem.Name},{subitem.DepartmentId}"); // } // Console.WriteLine(); //} //从结果来看 //1、GroupJoin 和数据库的 left outer join 一样 //public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector) //2、Func<TOuter, IEnumerable<TInner>, TResult> resultSelector 也就是 GroupJoin中的(a, blist) blist类型是 IEnumerable<TInner> } } public class UserDepart { public long UserId { get; set; } public long DepartmentId { get; set; } public string Name { get; set; } } public class NoticeData { public long Id { get; set; } public long DepartmentId { get; set; } public string Name { get; set; } } }
控制台项目ConsoleDemo的Program添加 如下:
Testlinq testlinq = new Testlinq(); testlinq.Testjoin(); testlinq.TestGroupjoin();
运行结果: