Remove Items From One List That Exist in Another List by ID in C#
Sometimes you need to remove elements from one collection if they already exist in another collection. The comparison is usually based on an identifier (ID). After testing several approaches, this turned out to be the cleanest and most readable solution using LINQ: lst1.RemoveAll(itemFromLst1 => lst2.Any(itemFromLst2 => itemFromLst2.ID == itemFromLst1.ID)); What This Code Does The logic can be read as: For each item in lst1 Check if any item in lst2 has the same ID If yes — remove it from lst1 In other words, this removes all elements from lst1 whose IDs already exist in lst2 . Why This Approach Works Well Concise and expressive No manual loops required No temporary collections needed Uses built-in List<T>.RemoveAll method The method RemoveAll modifies the list in place, which is often exactly what you want in filtering scenarios. Performance Consideration This solution uses Any() inside RemoveAll() , which means it performs a nest...