1.概要
左连接是很常用的方法。
2.代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 表对象化链表排序
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
Console.WriteLine("表对象化链表排序");
Program p = new Program();
p.main();
Console.ReadKey();
}
private void main()
{
test_groupJoin();
//test_join();
//test_leftJoin();
//test2();
}
private void test_groupJoin()
{
var groupList = A.getList().GroupJoin(B.getList(), a => a.bid, b => b.id, (a, b) => new { a.ns, a.id, b });
foreach (var a in groupList)
{
Console.WriteLine(a.id + " " + a.ns + " ");
var c = a.b;
var d = c.Select(h => new { h.ns2 }).FirstOrDefault();
if (d != null)
{
Console.WriteLine(d.ns2);
}
Console.WriteLine();
}
}
private void test_join()
{
var tlist = from a in A.getList() join b in B.getList() on a.bid equals b.id select new { a.id,a.ns,bid= b.id,b.ns2};
foreach(var it in tlist)
{
Console.WriteLine(it.id + " " + it.ns);
}
}
private void test_leftJoin()
{
var tlist = from a in A.getList() join b in B.getList() on a.bid equals b.id
into dd
from dt in dd.DefaultIfEmpty()
select new { a.id, a.ns, bid = dt==null?0:dt.id, ns2 = dt==null?"":dt.ns2};
foreach (var it in tlist)
{
Console.WriteLine(it.id + " " + it.ns+ " "+it.ns2);
}
}
private void test2()
{
List<List<int>> numbers = new List<List<int>>(){
new List<int>{1,2,3},
new List<int>{4,5,6},
new List<int>{7,8,9}
};
var result = numbers.SelectMany(collection => collection);
foreach (var item in result)
{
Console.WriteLine(item);
}
}
}
public class A
{
public int id;
public string ns;
public int bid;
public A(int id,string n,int bid) {
this.id = id;
this.ns = n;
this.bid = bid;
}
public static List<A> getList()
{
List<A> li = new List<A>();
li.Add(new A(1, "a1",1));
li.Add(new A(2, "a2",2));
li.Add(new A(3, "a3",0));
return li;
}
}
public class B
{
public int id;
public string ns2;
public B(int id,string n)
{
this.id = id;
this.ns2 = n;
}
public static List<B> getList()
{
List<B> li = new List<B>();
li.Add(new B(1, "b1"));
li.Add(new B(2, "b2"));
return li;
}
}
}
3.运行结果
3.1 test_groupJoin();
表对象化链表排序
1 a1
b1
2 a2
b2
3 a3
3.2 test_join
表对象化链表排序
1 a1
2 a2
3.3 test_leftJoin();
表对象化链表排序
1 a1 b1
2 a2 b2
3 a3
4.参考连接
如何在EF中实现left join(左联接)查询_ef left join_菜鸟de成长历程的博客-CSDN博客
ef 使用left join的两种写法_ef left join_看月亮的向月葵的博客-CSDN博客
EF 实现left join左联接查询_51CTO博客_querywrapper left join
https://www.cnblogs.com/keeplearningandsharing/p/16625086.html