Dave
Dave

Reputation: 125

Filtering 2 lists in a performant way

I have 2 lists:

newUpdates and updatesToAdd

I first of all need to remove all the occurrences of updatesToAdd from the newUpdates list by their Id. Then I need to add all updatesToAdd back into newUpdates to prevent duplicates.

It may not be clear why I'm doing this, but I need to swap out multiple occurrences of items that share the same Id (different update type) to then reinsert just one item for that Id with a main/master/catch all update type.

The code I have so far does this, but it runs very slowly. Is there a more performant way to write this?

    var newUpdates = new List<Entity>();
    var updatesToAdd = new List<Entity>();

    var Ids = updatesToAdd.Select(x => x.Id).ToList();
    newUpdates.RemoveAll(x => Ids.Contains(x.Id));
    newUpdates.AddRange(updatesToAdd);

I tried doing:

    newUpdates.Union(updatesToAdd).ToList();

However, I still ended up with duplicates in my list.

Upvotes: 0

Views: 52

Answers (1)

user5292841
user5292841

Reputation:

Why not use Except instead? https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except?view=netframework-4.7.2

or Contains is false.

In fact I think you have a bug. I think you want to do this:

var newUpdates = new List<Entity>(); //overall list to add
var updatesToAdd = new List<Entity>();  //later list to add

var Ids = updatesToAdd.Select(x => x.Id).ToList();  //this line chagned
newUpdates.RemoveAll(x => Ids.Contains(x.Id));
newUpdates.AddRange(updatesToAdd);

Upvotes: 1

Related Questions