LINQ比较两个列表并删除 [英] LINQ compare two lists and remove

查看:107
本文介绍了LINQ比较两个列表并删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表.我想从LIST1删除LIST2中不存在的所有项目.

I have two lists. I want to remove any items from LIST1 that are NOT present in LIST2.

例如:

        var list1 = new List<DownloadTask>();
        list1.Add(new DownloadTask{ OperationID = 1, MachineID = 1 });
        list1.Add(new DownloadTask{ OperationID = 2, MachineID = 1 });
        list1.Add(new DownloadTask{ OperationID = 3, MachineID = 1 });
        list1.Add(new DownloadTask{ OperationID = 3, MachineID = 2 });

        var list2 = new List<DownloadTask>();
        list2.Add(new DownloadTask{ OperationID = 1, MachineID = 1 });
        list2.Add(new DownloadTask{ OperationID = 3, MachineID = 2 });

运行后,list1应仅包含以下项目:组合为operationId = 1machineId = 1OperationId = 3MachineId =2.

After run list1 should contain only items: with combination operationId = 1, machineId = 1 AND OperationId = 3, MachineId =2.

推荐答案

DownloadTask是否正确覆盖EqualsGetHashCode?如果是这样,您只需要:

Does DownloadTask override Equals and GetHashCode correctly? If so, all you need is:

list1 = list1.Intersect(list2).ToList();

当然,如果您很高兴创建一个新列表.如果您真的要从现有列表中删除它们,则要困难一些.弄清楚结果应该是什么样,然后清除并重新添加,将是最简单的:

That's if you're happy to create a new list, of course. If you really want to remove them from the existing list, it's slightly harder. It would quite possibly be simplest to work out what the result should look like, then clear and re-add:

var newList = list1.Intersect(list2).ToList();
list1.Clear();
list1.AddRange(newList);

当然,所有这些都要求您在DownloadTask中适当地实现相等-但是,如果您还没有这样做,那么听起来这样做是个好主意. . (或者至少在某个地方实现IEqualityComparer<DownloadTask>-您可以将比较器传递给Intersect.)

Of course, all of this does require you to implement equality appropriately in DownloadTask - but if you haven't done so already, it sounds like it would be a good idea to do so. (Or at least implement IEqualityComparer<DownloadTask> somewhere - you can pass a comparer to Intersect.)

作为旁注,我认为仅将list1中的元素也保留在list2中"(即交集)比从list1中删除所有元素不在list2中"-后者基本上是双重否定的,总是有点痛苦.

As a side note, I view "only keep the elements in list1 which are also in list2" (i.e. intersection) as a simpler way of looking at the problem than "remove all elements from list1 which aren't in list2" - the latter is basically a double negative, which is always a bit of a pain.

这篇关于LINQ比较两个列表并删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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