Linq查询查找重复项并将其从列表中删除 [英] Linq query that finds duplicates and removed them from a list

查看:68
本文介绍了Linq查询查找重复项并将其从列表中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个LINQ查询,该查询将在2个列表中查找重复项并将其从第一个列表中删除.

I'm trying to create a LINQ query that will look for duplicates in 2 lists and remove them from the first list.

下面的代码将找到重复项并将其返回,但是我希望查询从NotificationsFirst返回唯一项:

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
    }
}

推荐答案

您应结合使用 Except 方法和 Intersect .

想法是使用 Intersect 找出给定初始列表的 intersection 列表,然后从第一个仅仅 Except >收藏.

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));

这篇关于Linq查询查找重复项并将其从列表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆