开发者

remove item in list based on item of other list

开发者 https://www.devze.com 2023-03-03 11:51 出处:网络
How do I remove items from one list based on items in other list? Basically I want to compare list1 and list2 and the the difference each item in these lists should removed.

How do I remove items from one list based on items in other list?

Basically I want to compare list1 and list2 and the the difference each item in these lists should removed.

ex: I have a class call Dog

class Dog
{
   private string _name;
    public string Name
        {
            get { return selisih; }
            set { selisih = value; }
        }

}

in winform

list<Dog> Dog1 = new list<Dog>();
list<Dog> Dog2 = new list<Dog>();

and add items to开发者_StackOverflow中文版 this list. How should I do to compare these two lists? and when items in Dog1 did not exist in Dog2. Those items should be deleted or removed from Dog1.


Use LINQ - the Except method should do.

var dog3 = Dog1.Except(Dog2).ToList();

You will probably need to pass in a function that compares dogs, so it knows how to do this.

Untested:

var dog3 = Dog1.Except(Dog2, (d1, d2) => d1.Name.CompareTo(d2.Name)).ToList();


you can do it in LINQ like

Dog1.ForEach(x => 
            {
                if (!Dog2.Select(z=>z.Name).Contains(x.Name)) 
                {
                    Dog1.Remove(x);
                }
            });


Your best bet would be to loop over the list you need to synchronize using List.Contains() to check if the item exists.

For example:

For Each Dog As Dog In Dog1
If Dog2.Contains(Dog) = False Then
Dog2.Add(Dog)
End If
End For

To add items that don't exist in the second list, but do in the first.

0

精彩评论

暂无评论...
验证码 换一张
取 消