Moving an object in the list, deleting and returning it

Possible duplicate:
C #: how to remove an element inside IEnumerable

I have an Inumerable of Objects foo .

  public IEnumerable<foo> listOfFoo{ get; set; } 

Foo has an id and the name lets say.

I want to pass an identifier to a method, and the method should remove an object with this ID from IEnumerable and return it.

What is the best way to do this?

+4
source share
4 answers

This is not possible for any collection that implements IEnumerable<foo> . If it is, for example, List<foo> , then you can delete elements for it, but if it is, for example, foo[] , you cannot delete elements.

If you use List<foo> instead:

 public foo Extract(int id) { int index = listOfFoo.FindIndex(x => x.Id == id); foo result = listOfFoo[index]; listOfFoo.removeAt(index); return result; } 
+3
source

IEnumerable read-only. You cannot delete an object from one.

However, you could do something like

 public Foo QuoteRemoveUnquoteById(int id) { var rtnFoo = listOfFoo.SingleOrDefault(f => f.Id == id); if (rtnFoo != default(Foo)) { listOfFoo = listOfFoo.Where(f => f.Id != id); } return rtnFoo; } 

which just masks matching Foo ? However, this will become less and less, the more objects that you β€œdelete”. Also, nothing that contains a link to listOfFoo will see any changes.

+5
source

You cannot just remove an element from IEnumerable .


But you can either make changes to the base collection (for example, if it is a List or something else), or filter out IEnumerable using the Where clause.

If you need to delete items, you must use a collection that supports the removal of items, such as List<> .


For example, you might have your background field of type List<foo> :

 private List<foo> _listOfFoo; public IEnumerable<foo> listOfFoo { get { return _listOfFoo.AsReadOnly(); } set { _listOfFoo = value.ToList(); } } 

And then remove the items from _listOfFoo .

 _listOfFoo.Remove(_listOfFoo.Single(foo => foo.ID == id_to_remove)); 
+3
source

IEnumarable is an interface for iterating through a collection, and there is no way to remove items without casting to some collection.

read here:

http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx

+2
source

Source: https://habr.com/ru/post/1436766/


All Articles