Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing item from list with RemoveAll

Tags:

c#

lambda

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

like image 309
hoakey Avatar asked Jun 29 '11 15:06

hoakey


People also ask

How do I remove an item from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.

How do you remove something from a list while iterating?

If you want to delete elements from a list while iterating, use a while-loop so you can alter the current index and end index after each deletion.

How do you remove an item from a list using its index?

You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output. You can also use negative index values.

How do I remove an object from a list in Python?

To remove items (elements) from a list in Python, use the list functions clear(), pop(), and remove(). You can also delete items with the del statement by specifying a position or range with an index or slice.


1 Answers

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"));
like image 178
dkackman Avatar answered Oct 23 '22 13:10

dkackman