离开加入 Linq?

2

本文介绍了离开加入 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14