C# 使用 linq 从列表中删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12975306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:10:06  来源:igfitidea点击:

Remove item from list using linq

c#linq

提问by Neeraj Kumar Gupta

How to remove item from list using linq ?.

如何使用 linq 从列表中删除项目?

I have a list of items and each item it self having a list of other items now I want to chaeck if other items contains any items of passed list so main item should be remove. Please check code for more clarity.

我有一个项目列表,每个项目本身都有一个其他项目的列表,现在我想检查其他项目是否包含传递列表中的任何项目,因此应该删除主要项目。请检查代码以获得更清晰的信息。

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));

}

采纳答案by Jan P.

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

回答by Pranay Rana

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

or

或者

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

回答by flindeberg

Just to point out, LINQ is for querying data and you will not actually remove the element from the original container. You will have to use _lstBase.Remove(item)in the end. What you can do is to use LINQ to find those items.

只是指出,LINQ 用于查询数据,您实际上不会从原始容器中删除元素。你最终将不得不使用_lstBase.Remove(item)。您可以做的是使用 LINQ 来查找这些项目。

I am assuming that you are using some kind of INotify pattern where it is pattern breaking to replace _lstBasewith a filtered version of itself. If you can replace _lstBase, go with @JanP.'s answer.

我假设您正在使用某种 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);
}