简体   繁体   English

从列表1中删除不在列表2中的项目

[英]Remove items from list 1 not in list 2

I am learning to write lambda expressions , and I need help on how to remove all elements from a list which are not in another list. 我正在学习编写lambda表达式 ,我需要有关如何从列表中删除不在另一个列表中的所有元素的帮助。

var list = new List<int> {1, 2, 2, 4, 5};
var list2 = new List<int> { 4, 5 };

// Remove all list items not in List2
// new List Should contain {4,5}    
// The lambda expression is the Predicate.
list.RemoveAll(item => item. /*solution expression here*/ );

// Display results.
foreach (int i in list)
{
    Console.WriteLine(i);
}

You can do this via RemoveAll using Contains: 您可以使用Contains通过RemoveAll执行此操作:

list.RemoveAll( item => !list2.Contains(item));

Alternatively, if you just want the intersection, using Enumerable.Intersect would be more efficient: 或者,如果您只想要交集,使用Enumerable.Intersect会更有效:

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

The difference is, in the latter case, you will not get duplicate entries. 不同的是,在后一种情况下,您将不会获得重复的条目。 For example, if list2 contained 2, in the first case, you'd get {2,2,4,5} , in the second, you'd get {2,4,5} . 例如,如果list2包含2,则在第一种情况下,您将获得{2,2,4,5} ,在第二种情况下,您将获得{2,4,5}

Solution for objects (maybe easier than horaces solution): 对象的解决方案 (可能比horaces解决方案更容易):

If your list contains objects, rather than scalars, it is that simple, by removing by one selected property of the objects: 如果您的列表包含对象而不是标量,那么通过删除对象的一个选定属性就可以了:

    var a = allActivePatientContracts.RemoveAll(x => !allPatients.Select(y => y.Id).Contains(x.PatientId));

This question has been marked as answered, but there is a catch. 这个问题已被标记为已回答,但有一个问题。 If your list contains an object, rather than a scalar, you need to do a bit more work. 如果列表包含对象而不是标量,则需要做更多的工作。

I tried this over and over with Remove() and RemoveAt() and all sorts of things and none of them worked correctly. 我一遍又一遍地尝试使用Remove()和RemoveAt()以及各种各样的东西,但没有一个能正常工作。 I couldn't even get a Contains() to work correctly. 我甚至无法让Contains()正常工作。 Never matched anything. 从来没有匹配过。 I was stumped until I got the suspicion that maybe it could not match up the item correctly. 我很难过,直到我怀疑它可能无法正确匹配项目。

When I realized this, I refactored the item class to implement IEquatable, and then it started working. 当我意识到这一点时,我重构了item类来实现IEquatable,然后它开始工作了。

Here is my solution: 这是我的解决方案:

class GenericLookupE : IEquatable<GenericLookupE>
{
    public string   ID  { get; set; }

    public bool     Equals( GenericLookupE other )
    {
        if ( this.ID == other.ID )      return true;

        return false;
    }
}

After I did this, the above RemoveAll() answer by Reed Copsey worked perfectly for me. 在我这样做之后,Reed Copsey的上述RemoveAll()回答对我来说非常合适。

See: http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx 请参阅: http//msdn.microsoft.com/en-us/library/bhkz42b3.aspx

list = list.Except(list2).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM