Neeraj Kumar Gupta
Neeraj Kumar Gupta

Reputation: 2363

Remove item from list using linq

How to remove item from list using 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));

}

Upvotes: 13

Views: 45829

Answers (3)

flindeberg
flindeberg

Reputation: 5027

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.

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

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

Upvotes: 7

Pranay Rana
Pranay Rana

Reputation: 176956

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

Upvotes: 3

Jan P.
Jan P.

Reputation: 3297

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

Upvotes: 22

Related Questions