0

Good Morning, I have a list of person

private List<Person> person = new List<Person>();

Person is a class

public class Person
{
    public double trackID; 
    int Age;
}

I would like remove the item that have a particular ID (ID2 in the code). How can i do?

i try this but i have some error exceptions:

foreach (Person p in person)
{
   if (p.ID == ID2)
   {
     person.Remove(p);
   }
}

thank you in advance for your cooperation

Skipper
  • 83
  • 1
  • 2
  • 8
  • You won't be able to remove items from the list while iterating over it (e.g. [this StackOverflow question](http://stackoverflow.com/q/4536090/1364007)). You can instead use use the [Where](https://msdn.microsoft.com/en-us/library/vstudio/bb534803) method: `person.Where(p => p.ID != ID2)`. – Wai Ha Lee Feb 02 '15 at 10:53
  • Also, a stylistic issue, but it's a bit confusing to have a collection named in the singular. It'd be less confusing to call it `persons` or `people`. – Wai Ha Lee Feb 02 '15 at 10:54

1 Answers1

3

You can use Linq as show below:

var person.RemoveAll(x => x.ID == ID2);
a.azemia
  • 304
  • 1
  • 6