2011-07-22 133 views
2

有這樣做左外至少有兩種方法在LINQLINQ左外連接語法差異

class Customer 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
} 

class Order 
{ 
    public int ID { get; set; } 
    public string Product { get; set; } 
} 

    static void Main() 
    { 
     // Example customers. 
     var customers = new Customer[] 
     { 
      new Customer{ID = 5, Name = "Sam"}, 
      new Customer{ID = 6, Name = "Dave"}, 
      new Customer{ID = 7, Name = "Julia"}, 
      new Customer{ID = 8, Name = "Sue"}, 
      new Customer{ID = 9, Name = "Joe"} 
     }; 

     // Example orders. 
     var orders = new Order[] 
     { 
      new Order{ID = 5, Product = "Book"}, 
      new Order{ID = 6, Product = "Game"}, 
      new Order{ID = 7, Product = "Computer"}, 
      new Order{ID = 8, Product = "Shirt"}, 
      new Order{ID = 8, Product = "TShirt"} 
     }; 


     // First Way 
     var query = from c in customers 
       join o in orders on c.ID equals o.ID into co 
       from x in co.DefaultIfEmpty() 
       where x != null && x.Product == "Shirt" 
       select new {c, x}; 

     // Second Way 
     var query2 = from c in customers 
        from o in orders 
        where c.ID == o.ID && o.Product == "Shirt" 
        select new {c, o}; 
    } 

JOIN我發現(使用「到」)有很多的第一種方式的例子,那就是這樣我曾經做過我的左外連接。最近我找到了第二條路,看起來更簡單。我測試了它們並且它們都產生了相同的結果。現在我的問題是否存在任何隱藏的差異,表現,還是僅僅是語法糖?

非常感謝。

+4

,想必這應該只是一個直內加入因!= NULL檢查? –

回答

6

第一種方式,應使用,如果你不使用!= NULL檢查

左外連接所有匹配右表,如果不存在匹配的項目選擇一切從左表在右表中,結果仍然返回,但右表中的值爲空(linq將其轉換爲集合項類型的默認值)

這兩個查詢都有效地執行內連接,因此它們將會相同。

要爲什麼地球上您使用左外連接,得到不同的結果

// First Way 
var query = from c in customers 
join o in orders on c.ID equals o.ID into co 
from x in co.DefaultIfEmpty() 
where c.Id>5 
select new {c, x}; 

// Second Way 
var query2 = from c in customers 
from o in orders 
where c.ID == o.ID && c.ID > 5 
select new {c, o}; 
+0

感謝鮑勃。你是對的,如果我使用!= null檢查,他們在這種情況下都是內連接。再次感謝。 –