Removing an item from a list using RemoveAll

I am trying to use a lambda expression to remove a specific object from a list based on the value inside that object. Here is my lambda:

ChartAttributes.ToList().RemoveAll(a => a.AttributeValue.Contains("PILOT")); 

Here is a list of ChartAttributes

 IList<IChartAttribute> ChartAttributes 

Here is the ChartAttribute object contained in the above list

  public virtual string AttributeKey { get; set; } public virtual string AttributeValue { get; set; } public virtual int ChartAttributeId { get; set; } public virtual int ChartSpecificationId { get; set; } 

There is a chart attribute with its AttributeKey attribute set to "PILOT". But it is never deleted. What am I doing wrong?

thanks

+4
source share
4 answers

Your code accepts IEnumerable , copies all its elements to the list, and then removes the elements from this copy. The IEnumerable source does not change.

Try the following:

 var list = ChartAttributes.ToList(); list.RemoveAll(a => a.AttributeValue.Contains("PILOT")); ChartAttributes = list; 

EDIT

Actually the best way, without calling ToList :

 ChartAttributes = ChartAttributes.Where(a => !a.AttributeValue.Contains("PILOT")); 
+11
source

Your call to .ToList() creates a new list and you remove the item from this list.

Whatever the ChartAttributes , you do not touch its contents.

You basically do this:

 var newList = ChartAttributes.ToList(); newList.RemoveAll(...); 

If you were to check the contents of newList , at that moment you would notice that your object was deleted, but ChartAttributes, any type that is, still has these objects.

You will need to remove the objects directly from the ChartAttributes, but since you did not specify what type it is, I cannot give you an example of how to do this.

+9
source

If you need to delete items and save to the database, you can try this sample code:

 foreach (var x in db.myEntities.Where(a => a.AttributeValue.Contains("PILOT"))) db.myEntities.Remove(x); db.SaveChanges(); 

It does not use RemoveAll, but it is another option for saving content.

+1
source

I had a similar problem and listing was done instead (since my installer for the property was internal):

 ((List<IChartAttribute>)ChartAttributes).RemoveAll(a => a.AttributeValue.Contains("PILOT")); 
+1
source

All Articles