左联接,右为空

时间:2020-01-22 16:14:21

标签: c# linq

我试图在C#中退出联接以仅从Foo中查找不在Bar中的值。 在SQL中,我通常会这样做:

SELECT * FROM FOO f
LEFT JOIN BAR b ON f.ID = b.ID
WHERE b.ID IS NULL

我通常使用linq做这样的事情:

var matches = Foos.Join(
    Bars,
    foo => foo.ID,
    bar => bar.ID,
    (foo, bar) => foo
).Select(x => x.ID);

然后:

var noMatch = Foos.Where(x => !matches.Contains(x.ID));

现在要问的是:.Join()函数中是否有办法实现这一目标?

3 个答案:

答案 0 :(得分:3)

您可以如下图所示进行左联接:

var query= from f in Foos
           join b in Bars on f.Id equals b.Id into gb
           from sb in gb.DefaulfIfEmpty()
           where sb.ID==null
           select {f, sb};

答案 1 :(得分:1)

做这样的事情:

Foos.
.GroupJoin(
    Bars,
    f => f.Id,
    b => b.Id,
    (f, lj) => new { f, lj })
    .SelectMany(t => t.lj.DefaultIfEmpty(),
            (t, b) => new { 
                foo = t.f,
                bar = b
                })
    .Where(a => a.bar.Any() == false)
    .ToList()   

答案 2 :(得分:0)

查询语法版本已得到解答,但我个人更喜欢方法语法:

var result = Foos
  .GroupJoin(
    Bars,
    f => f.ID,
    b => b.ID,
    (fos, bas) => new { Foo = fos, Bar = bas })
  .SelectMany(
    sum => sum.Bar.DefaultIfEmpty(),
    (sum, flatBar) => new 
    {
      Foo = sum.Foo,
      Bar = flatBar
    })
  .Where(anon => !anon.Bar.Any());