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
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"));
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.
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.
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"));
精彩评论