【发布时间】:2021-04-12 02:45:01
【问题描述】:
我正在尝试创建一个 LINQ 查询,它将在 2 个列表中查找重复项并将它们从第一个列表中删除。
下面的代码将找到重复项并返回它们,但我希望查询返回来自 notificationsFirst 的唯一项目:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
InnerJoinExample();
Console.ReadLine();
}
class Notification
{
public string Name { get; set; }
public int Id { get; set; }
}
public static void InnerJoinExample()
{
Notification first = new Notification { Name = "First", Id = 1 };
Notification second = new Notification { Name = "Second", Id = 2 };
Notification third = new Notification { Name = "Third", Id = 3 };
Notification fourth = new Notification { Name = "Fourth", Id = 4 };
Notification fifth = new Notification { Name = "Fifth", Id = 5 };
List<Notification> notificationsFirst = new List<Notification> { first, second, third };
List<Notification> notificationsSecond = new List<Notification> { third, fourth, fifth };
var query = from notiFirst in notificationsFirst
join notiSecond in notificationsSecond on notiFirst.Id equals notiSecond.Id
select new Notification { Name = notiFirst.Name, Id = notiFirst.Id };
foreach (var not in query)
{
Console.WriteLine($"\"{not.Name}\" with Id {not.Id}");
}
}
// This code should produce the following:
//
// "First" with Id 1
// "Second" with Id 2
}
}
【问题讨论】: