Click here to Skip to main content
15,890,186 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a List* <plantcollection> _PlantCollection list which contains 5 properties.

C#
class PlantCollection
    {
        private readonly Parser cParser = new Parser();
        public string Name { get; set; }
        public string SafeToFeed { get; set; }
        public string URLOfPlant { get; set; }
        public BitmapImage PlantThumbnail { get; set;}
        public string PlantTrafficColour { get; set; }
}


How would I remove a item from the list based on a condition of a single value?

E.g

If Safe To Feed contains ("Do Not Feed").. remove item. I tried using an the index of the item but it just return as -1.

I tried this but returns an exception - "collection has been modified"

C#
int i = 0;
foreach (PlantCollection plant in cParser._PlantCollection)
{
    if (cParser._PlantCollection[i].SafeToFeed.Contains("green"))
    {
        cParser._PlantCollection.Remove(plant);
        i++;
    }


}



Posted
Updated 12-Aug-13 0:33am
v5

1 solution

I would do something similar to this

C#
//Find all items that contain "Do Not Feed"
List<plantcollection> DataToRemove = Container.PlantCollection.FindAll(p=> p.SafeToFeed.Contains("Do Not Feed") == true);

if(DataToRemove != null)
{
  foreach(PlantCollection item in DataToRemove)
  {
    Container.PlantCollection.Remove(item);
  }
}
 
Share this answer
 
v2
Comments
SteveBaldwin21 12-Aug-13 6:37am    
Thank you for the reply. I tried this but VS2010 did not recongize the Container.PlantCollection?
Simon_Whale 12-Aug-13 6:39am    
you would replace Container.PLantCollection for cParser._PlantCollection
SteveBaldwin21 12-Aug-13 6:43am    
Oh! Sorry, Thank you!
SteveBaldwin21 12-Aug-13 7:09am    
Ignore this. I made a copy of the list so that it would not directly affect it.

Thank you anyway!
Simon_Whale 12-Aug-13 7:23am    
You could do something similar but you would have to loop through the items collection to view each data record

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900