离开加入 Linq?

Left join in Linq?(离开加入 Linq?)
本文介绍了离开加入 Linq?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

关于 Linq 中的左连接已经有很多关于 SO 的问题,我看过的问题都使用 join 关键字来实现所需的结果.

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.

这对我来说没有意义.假设我有 CustomerInvoice 表,它们由 Invoice 上的外键 CustomerID 链接.现在我想运行一个包含客户信息以及任何发票的报告.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 };

我真的不明白这怎么可能是唯一的方法.CustomerInvoice 之间的关系已经由 LinqToSQL 类定义;为什么我必须为 join 子句重复它?如果我想要一个内部连接,那就是:

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 };

没有指定连接的字段!

我试过了:

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.

没有更好的方法吗?

推荐答案

你在说什么?那个 from i in 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?(Linq to SQL 中是否提供 Unpivot(非 Pivot)功能?如何?)
How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)