我使用外键连接两个表。TABLE_1可能有一行的外键为null。这意味着,当我基于外键连接两个表时,我不会得到结果。我的问题是,当我在LINQ中使用join两个表,我会得到一个空的结果集。
我希望能够获得TABLE_1中的行,即使JOIN结果与TABLE_2不匹配。
我尝试在TABLE_2的联接中使用DefaultIfEmpty,但仍然得到一个空的结果集。即使TABLE_1在用于联接两个表的外键中包含null,我如何联接两个表格并仍然得到结果?
感谢
Hi尝试从表2到表1的左联接
class Program
{
static void Main(string[] args)
{
List<Table1> Table_1 = new List<Table1>();
Table_1.Add(new Table1() { Id = 1, Name = "Lion" });
Table_1.Add(new Table1() { Id = 2, Name = "Elephant" });
List<Table2> Table_2 = new List<Table2>();
Table_2.Add(new Table2() { Id = 1, Class = "Carnivorous" });
Table_2.Add(new Table2() { Id = 2, Class = "Herbivorous" });
Table_2.Add(new Table2() { Id = 3, Class = "Mammal" });
Table_2.Add(new Table2() { Id = 4, Class = "Aquarious" });
var result = (from a in Table_2
join b in Table_1
on a.Id equals b.Id into leftJoin
from c in leftJoin.DefaultIfEmpty()
select new { Id = a.Id, Name = c == null ? string.Empty : c.Name, Class = a.Class }
).ToList();
var abc = result;
}
}
public class Table1
{
public int Id;
public string Name;
}
public class Table2
{
public int Id;
public string Class;
}
如果LEFT JOIN不起作用,请尝试RIGHT JOIN。