从列表C#中删除项目

时间:2015-10-13 17:09:37

标签: c# .net linq

我有两个对象列表,我必须删除另一个列表中删除的值的'原始'列表;但该项目由两个属性标识。 我能够这样做,当对象只被一个属性识别时,但现在我需要检查两个属性

// 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

1 个答案:

答案 0 :(得分:3)

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

应该是对的,但不是最佳的。 (O ^ 2)