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:
What This Code Does
The logic can be read as:
- For each item in
lst1 - Check if any item in
lst2has the sameID - 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 nested scan.
For small or medium-sized lists, this is perfectly fine.
If both lists are very large, consider pre-building a HashSet<int> (or whatever type ID is) from lst2 to reduce lookup time.
Typical Use Cases
- Filtering duplicates before insert
- Synchronizing two collections
- Removing already processed records
- Cleaning up in-memory cache data
This one-liner is simple, readable, and reliable for most practical scenarios.
Comments
Post a Comment