问题
I'm trying to create a LINQ query that will look for duplicates in 2 lists and remove them from the first list.
The code bellow will find the duplicate and return them, but I would like the query to return the unique items from 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
}
}
回答1:
You should use Except
method in combination with Intersect
.
The idea is to find out the intersection list of the given initial lists using Intersect
and then just Except
that list from first collection.
var query = notificationsFirst.Except(notificationsFirst.Intersect(notificationsSecond));
来源:https://stackoverflow.com/questions/65594332/linq-query-that-finds-duplicates-and-removed-them-from-a-list