左Linq中加入吗? [英] Left join in Linq?

查看:79
本文介绍了左Linq中加入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多关于SO已经有大约左Linq中的联接问题,我看了所有的那些使用加入关键字达到理想的终点。

There are a lot of questions on SO already about Left joins in Linq, and the ones I've looked at all use the join keyword to achieve the desired end.

这是没有道理给我。比方说,我有表客户发票,由外键联系客户ID 发票。现在,我想运行一个包含客户信息的报告,以及任何发票。 SQL是:

This does not make sense to me. Let's say I have the tables Customer and Invoice, linked by a foreign key CustomerID on Invoice. Now I want to run a report containing customer info, plus any invoices. SQL would be:

select c.*, i.*
  from Customer c
  left join Invoice i on c.ID = i.CustomerID

这是我所看到的答案在SO,人们大多提示:

From what I've seen of the answers on SO, people are mostly suggesting:

var q = from c in Customers
        join i in Invoices.DefaultIfEmpty() on c.ID equals i.CustomerID 
        select new { c, i };



我真不明白这是如何的唯一途径。 客户之间的关系发票已经由LinqToSQL类中定义;为什么我应该重复它为加入条款?如果我想要一个内部联接它只会一直:

I really don't understand how this can be the only way. The relationship between Customer and Invoice is already defined by the LinqToSQL classes; why should I have to repeat it for the join clause? If I wanted an inner join it would simply have been:

var q = from c in Customers
        from i in c.Invoices
        select new { c, i };



在不指定加盟领域!

without specifying the joined fields!

我想:

var q = from c in Customers
        from i in c.Invoices.DefaultIfEmpty()
        select new { c, i };



但只是给了我同样的结果,好像它是一个内连接。

but that just gave me the same result as if it were an inner join.

请问有没有这样做的更好的办法?

Is there not a better way of doing this?

推荐答案

你在说什么?这从我c.Invoice.DefaultIfEmpty()正是左连接。

What are you talking about? That from i in c.Invoice.DefaultIfEmpty() is exactly a left join.

        List<string> strings = new List<string>() { "Foo", "" };

        var q = from s in strings
                from c in s.DefaultIfEmpty()
                select new { s, c };

        foreach (var x in q)
        {
            Console.WriteLine("ValueOfStringIs|{0}| ValueOfCharIs|{1}|",
                x.s,
                (int)x.c);
        }

本测试将生成:

ValueOfStringIs|Foo| ValueOfCharIs|70|
ValueOfStringIs|Foo| ValueOfCharIs|111|
ValueOfStringIs|Foo| ValueOfCharIs|111|
ValueOfStringIs|| ValueOfCharIs|0|

这篇关于左Linq中加入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆