【问题标题】:Linq query that finds duplicates and removed them from a list [duplicate]查找重复项并将其从列表中删除的 Linq 查询 [重复]
【发布时间】: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
    }
}

【问题讨论】:

标签: c# linq


【解决方案1】:

您应该将Except 方法与Intersect 结合使用。

我们的想法是使用Intersect 找出给定初始列表的intersection 列表,然后从第一个collection 中找出该列表的Except

var query = notificationsFirst.Except(notificationsFirst.Intersect(notificationsSecond));

【讨论】:

  • 谢谢!奇迹般有效。在实际代码中,notificationSecond 实际上是一个 DBContext,我正在尝试对数据库异步执行此操作。 var query = notificationsFirst.Except(notificationsFirst.Intersect(await _context.Notifications)); 但是抱怨 DbSet 没有 GetAwaiter
  • @Q-bertsuit,你应该使用await _context.Notifications.ToListAsync()
  • 完美!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-02
相关资源
最近更新 更多