2014-01-29 36 views
0

我有這方面的工作外連接查詢:重新寫LINQ外部聯接與方法的語法

var outerJoin = from b in books 
       join p in publishers on b.PublisherName equals p.Name into joinedPublishers 
       from publisher in joinedPublishers.DefaultIfEmpty() 
       select new { b.Title, PublisherName = (publisher == null ? "No publisher" : publisher.Name) }; 

我試圖產生與方法的語法相同。到目前爲止我有這樣的:

outerJoin = books.GroupJoin(publishers, b => b.PublisherName, p => p.Name, (b, group) => new { b.Title, PublisherName = group.DefaultIfEmpty()}); 

但是,groupIEnumerable,當我需要的發佈者名稱的字符串。

回答

0

據我瞭解,你可以打電話

{ 
    b.Title, 
    PublisherName = group.Any()?group.First().Name: "No publisher"; 
} 
0

我還是設法與以下弄明白:

outerJoin = books.GroupJoin(publishers, 
          b => b.PublisherName, 
          p => p.Name, 
          (b, publisherGroup) => new { b.Title, publisherGroup}) 
       .SelectMany(x => x.publisherGroup.DefaultIfEmpty(), 
          (x, y) => new {x.Title, PublisherName = (y == null ? "No publisher" : y.Name)});