hoakey
hoakey

Reputation: 998

Removing item from list with RemoveAll

I'm trying to use a lambda expression to remove a certain object from a list, based on a value within that object. Here is my lambda:

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

Here is the ChartAttributes list

IList<IChartAttribute> ChartAttributes 

Here is the object ChartAttribute contained within 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 set to "PILOT". But this never gets removed. What am I doing wrong?

Thanks

Upvotes: 6

Views: 17728

Answers (4)

gm1886
gm1886

Reputation: 81

I had a similar problem and did a cast instead (as my setter for the property was internal):

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

Upvotes: 1

live-love
live-love

Reputation: 52366

If you need to remove items and save to 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 doesn't use RemoveAll, but it's another option to save the contents.

Upvotes: 1

dkackman
dkackman

Reputation: 15549

Your code is taking an IEnumerable, copying all of its elements into a list and then removing items from that copy. The source IEnumerable is not modified.

Try this:

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

EDIT

Actually a better way, without needing to call ToList:

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

Upvotes: 14

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391316

Your call to .ToList() makes a new list, and you end up removing the item from that list.

Whatever ChartAttributes is, you're not touching the contents of that.

Basically you're doing this:

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

If you were to inspect the contents of newList at this point you'd notice that your object(s) had been removed, but ChartAttributes, whatever type that is, still has those objects present.

You will have to remove the objects directly from ChartAttributes, but since you didn't say which type that is, I can't give you an example of how to do that.

Upvotes: 10

Related Questions