Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an object in a list, remove and return it [duplicate]

Possible Duplicate:
c#: how do I remove an Item inside IEnumerable

I have an Inumerable of Objects foo.

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

Foo has Id and name lets say.

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

Whats the best way of doing it?

like image 837
Diego Avatar asked Sep 28 '12 08:09

Diego


2 Answers

IEnumerables are read-only. You can't remove an object from one.

That said, 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 out the matching Foo? However, this will get less and less performant the more items you "remove". Also, anything else that holds a reference to listOfFoo won't see any change.

like image 118
Rawling Avatar answered Oct 01 '22 02:10

Rawling


That's not possible for any collection that implements IEnumerable<foo>. If it is for example a List<foo>, then it's possible to remove items for it, but if it is for example a foo[] it's not possible to remove items.

If you use a 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;
}
like image 28
Guffa Avatar answered Oct 01 '22 03:10

Guffa