Remove items from list 1 not in list 2

后端 未结 4 1357
我在风中等你
我在风中等你 2021-02-01 14:32

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.

var list = new List

        
4条回答
  •  不要未来只要你来
    2021-02-01 14:53

    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. I couldn't even get a Contains() to work correctly. 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.

    Here is my solution:

    class GenericLookupE : IEquatable
    {
        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.

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

提交回复
热议问题