[英]Ignore duplicated rows with LINQ
我想在加入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
謝謝
方法如下:
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 };
嘗試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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.