Remove items from list that intersect on property using Linq

前端 未结 2 653
滥情空心
滥情空心 2021-02-12 15:24

I have 2 lists of different objects (foo & bar) that share the same property lets call it id.

public List          


        
2条回答
  •  故里飘歌
    2021-02-12 15:52

    Try this:

    foo.RemoveAll(x=> !bar.Any(y=>y.Id==x.Id));
    

    !bar.Any(y=>y.Id==x.Id) will get if item is in bar collection and if it's not it will remove it from foo collection.

    Better solution using hashset O(n):

    var idsNotToBeRemoved = new HashSet(bar.Select(item => item.Id));                     
    foo.RemoveAll(item => !idsNotToBeRemoved.Contains(item.Id));
    

    source of second answer: https://stackoverflow.com/a/4037674/1714342

    EDIT:

    as @Carra said, first solution is good for small lists and second is more efficient for big lists.

提交回复
热议问题