我想在加入2个表后显示唯一的行:
图书
Id Title
12 Title 1
13 Title 2
14 Title 3
作者
Id BookId Name
1 12 Steeve
2 13 Michel
3 13 Robert
在作者表中多次发现BookId时,预期的结果是显示最后一个ID(最后一个条目):
我的实际LINQ代码
from book in Books
join author in Authors on book.Id equals author.BookId into gr1
from join1 in gr1.DefaultIfEmpty()
实际结果
BookId AuthorId
12 1
13 2
13 3
14 NULL
预期结果
BookId AuthorId
12 1
13 3
14 NULL
谢谢
答案 0 :(得分:1)
方法如下:
var query = from book in Books
join author in Authors on book.Id equals author.BookId into gr1
select new { BookId = book.Id, AuthorId = gr1.LastOrDefault()?.Id };
答案 1 :(得分:-1)
尝试where子句
from book in Books
join author in Authors on book.Id equals author.BookId into gr1
from join1 in gr1.DefaultIfEmpty()
where author.authorID != null