lsotov
lsotov

Reputation: 375

Remove item from List C#

I have two list of Objects and I have to delete to the 'original' list the values deleted in the other list; but the item is identified by two properties. I was able to do so, when the object was only identified by one property, but now I need to check on two properties

// library: object with deleted data 
// library = new List<Widget>() { new Widget() { Id = "1", Nbr = 1 }, new Widget() { Id = "3", Nbr = 2 } };
var allData = GetData();
// allData = new List<Widget>() { new Widget() { Id = "1", Nbr = 1 }, new Widget() { Id = "2", Nbr = 1 }, new Widget() { Id = "3", Nbr = 2 } };
// var itemsToDelete = allData.Where(w => library.All(p => p.Id != w.Id)).ToList(); // I would do this, if the identifier would be only Id

var itemsToDelete = allData.Where(w => library.All(p => p.Id != w.Id && p.Nbr != w.Nbr)).ToList(); // I need to check for two properties and I'm getting zero coincidences

Upvotes: 0

Views: 131

Answers (1)

denza
denza

Reputation: 66

var itemsToDelete = allData.Where(w => !library.Any(p => p.Id == w.Id && p.Nbr == w.Nbr)).ToList(); 

Should be right, but not optimal. (O^2)

Upvotes: 3

Related Questions