問題描述
如何使用 C# 中的 Lambda 表達式僅返回沒有來自另一個表的行的行 (How to return only rows where no rows from another table using Lambda Expressions in C#)
我有兩張桌子;Notification 和 SeenBy。
Notification:
Notification.Id
Notification.Timestamp
Notification.Message
SeenBy
SeenBy.Id
SeenBy.NotificationId
SeenBy.ClientId
SeenBy.Timestamp
我需要獲取行使用輔助表 SeenBy 來自以前未見過的表 Notification (Count=0)。
Linq 查詢或 Lambda 表達式是什麼?
參考解法
方法 1:
You can try something like this:
var seenNotificationIds = seenByCollection.Select(x => x.NotificationId).Distinct();
var seenNotifications = notifications.Where(x => seenNotificationIds.Contains(x.Id));
var notSeenNotifications = notifications.Except(seenNotifications);
notSeenNotifications.Dump();
方法 2:
You can use this code:
var allNotificationObjects = ...; // all your notification objects
var seenByObjects = ...; // all seen by objects
var seenNotificationIds = seenByObjects
.Select(item => item.NotificationId)
.Distinct()
.ToHashSet();
var result = allNotificationObjects
.Where(item => !seenNotificationsIds.Contains(item.Id))
.ToList(); // all notifications which are not seen
(by Nime Cloud、Mahdi、Roman)