如何使用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));
}
Run Code Online (Sandbox Code Playgroud)
Jan*_* P. 21
_lstBase
.RemoveAll(a => a.Appointmerts.Any(item => appointmentsToCheck.Contains(item)));
Run Code Online (Sandbox Code Playgroud)
需要指出的是,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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43218 次 |
| 最近记录: |