Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an element from a generic list

I can´t remove an element from an IEnumerable list, but this list is a reference to a List , a private attribute of an other class. If I put personsCollection.Remove(theElement) in the same class (class Manager), it works perfect, but I need to delete the element since the other class (class ManagerDelete). Please how can I do this? Thanks.

class Other
{
  //Some code
  public IEnumerable<Person> SearchByPhone (string value)
    {
        return from person in personCollection
               where person.SPhone == value
               select person;
    }
 }

class ManagerDelete
{ 
//Some code
IEnumerable<Person> auxList= SearchByPhone (value);
//I have a method for delete here  
}

class Manager
{ 
//Some code
 private List<Person> personsCollection = new List<Person>();
}
like image 219
Priscila Avatar asked Mar 27 '13 13:03

Priscila


2 Answers

You can't delete from an IEnumerable<T> you need to make it of type IList<T> to add/remove items directly from it.

like image 162
Darren Avatar answered Sep 28 '22 14:09

Darren


You need to understand what an IEnumerable Interface allows you to do.

I'v listed below the list of Interfaces that you should use by design, as and when required in differnt circumstances. In your example IList is what you will need to use.

  • ICollection Defines general characteristics (e.g., size, enumeration, and thread safety) for all non-generic collection types.

  • ICloneable Allows the implementing object to return a copy of itself to the caller.

  • IDictionary Allows a non-generic collection object to represent its
    contents using key/value pairs.

  • IEnumerable Returns an object implementing the IEnumerator interface (see next table entry).

  • IEnumerator Enables foreach style iteration of collection items.

  • IList Provides behavior to add, remove, and index items in a
    sequential list of objects.

like image 29
Derek Avatar answered Sep 28 '22 15:09

Derek