使用LINQ从列表中删除项目

13

如何使用linq从列表中删除元素?

我有一个项目列表,每个项目本身都有另一个项目列表,现在我想检查其他项目是否包含传递列表中的任何项目,那么主项目应该被删除。请查看代码以获得更多明确信息。

public Class BaseItems
{
    public int ID { get; set; }
    public List<IAppointment> Appointmerts { get; set; }
}

Public DeleteApp(List<IAppointment> appointmentsToCheck)
{
   List<BaseItems> _lstBase ; // is having list of appointments

   //now I want to remove all items from _lstBase  which _lstBase.Appointmerts contains 
   any item of appointmentsToCheck (appointmentsToCheck item and BaseItems.Appointmerts 
   item is having a same reference)

   //_lstBase.RemoveAll(a => a.Appointmerts.Contains( //any item from appointmentsToCheck));

}
3个回答

22
_lstBase
    .RemoveAll(a => a.Appointmerts.Any(item => appointmentsToCheck.Contains(item)));

7
只是提醒一下,LINQ 用于查询数据,实际上不会从原始容器中删除元素。最后你将不得不使用 _lstBase.Remove(item)。你可以使用 LINQ 查找这些元素。
我假设你正在使用某种 INotify 模式,在这种模式下,用过滤版本的自身替换 _lstBase 是破坏模式的。如果你可以替换 _lstBase,那么使用 @JanP. 的答案。
List<BaseItems> _lstBase ; // populated original list

Public DeleteApp(List<IAppointment> appointmentsToCheck)
{
  // Find the base objects to remove
  var toRemove = _lstBase.Where(bi => bi.Appointments.Any
                (app => appointmentsToCheck.Contains(app)));
  // Remove em! 
  foreach (var bi in toRemove)
    _lstBase.Remove(bi);
}

3
var data = 
   _lstBase.
    Except(a => a.Appointmerts.Any
        (item => appointmentsToCheck.Contains(item)));

或者
var data = 
   _lstBase.
    Where(a => !a.Appointmerts.Any
        (item => appointmentsToCheck.Contains(item)));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接