Left join in Linq?

后端 未结 3 1589
长发绾君心
长发绾君心 2020-12-16 06:52

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.

T

相关标签:
3条回答
  • 2020-12-16 07:05

    While the relationship is already defined (both in the database and in the .dbml markup) the runtime cannot automatically determine if it should use that relationship.

    What if there are two relationships in the object model (Person has Parents and Children, both relationships to other Person instances). While cases could be special cased, this would make the system more complex (so more bugs). Remember in SQL you would repeat the specification of the relationship.

    Remember indexes and keys are an implementation detail and not part of the relational algebra that underlies the relation model.

    If you want a LEFT OUTER JOIN then you need to use "into":

    from c in Customers
    join i in Invoices on i.CustomerId equals c.CustomerId into inv
    ...
    

    and inv will have type IEnumerable<Invoivce>, possibly with no instances.

    0 讨论(0)
  • 2020-12-16 07:20

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

    This test produces:

    ValueOfStringIs|Foo| ValueOfCharIs|70|
    ValueOfStringIs|Foo| ValueOfCharIs|111|
    ValueOfStringIs|Foo| ValueOfCharIs|111|
    ValueOfStringIs|| ValueOfCharIs|0|
    
    0 讨论(0)
  • 2020-12-16 07:27

    You may probably want to use the 'into' keyword.

    Example

    0 讨论(0)
提交回复
热议问题