score:76

Accepted answer

using linq:

prods.remove( prods.single( s => s.id == 1 ) );

maybe you even want to use singleordefault() and check if the element exists at all ...

edit:
since stuff is a struct, singleordefault() will not return null. but it will return default( stuff ), which will have an id of 0. when you don't have an id of 0 for your normal stuff-objects you can query for this id:

var stufftoremove = prods.singleordefault( s => s.id == 1 );
if( stufftoremove.id != 0 )
{
    prods.remove( stufftoremove );
}

score:-2

you could use linq.

var prod = from p in prods
           where p.id != 1
           select p;

score:0

you can only remove something you have a reference to. so you will have to search the entire list:

stuff r;
foreach(stuff s in prods) {
  if(s.id == 1) {
      r = s;
      break;
  }
}
prods.remove(r);

or

for(int i = 0; i < prods.length; i++) {
    if(prods[i].id == 1) {
        prods.removeat(i);
        break;
    }
}

score:0

prods.remove(prods.single(p=>p.id == 1));

you can't modify collection in foreach, as vincent suggests

score:1

here is a solution for those, who want to remove it from the database with entity framework:

prods.removewhere(s => s.id == 1);

and the extension method itself:

using system;
using system.linq;
using system.linq.expressions;
using microsoft.entityframeworkcore;

namespace livanova.ngpdm.client.services.data.extensions
{
    public static class dbsetextensions
    {
        public static void removewhere<tentity>(this dbset<tentity> entities, expression<func<tentity, bool>> predicate) where tentity : class
        {
            var records = entities
                .where(predicate)
                .tolist();
            if (records.count > 0)
                entities.removerange(records);
        }
    }
}

p.s. this simulates the method removeall() that's not available for db sets of the entity framework.

score:3

prods.remove(prods.find(x => x.id == 1));

score:8

if you have linq:

var itemtoremove = prods.where(item => item.id == 1).first();
prods.remove(itemtoremove)

score:238

if your collection type is a list<stuff>, then the best approach is probably the following:

prods.removeall(s => s.id == 1)

this only does one pass (iteration) over the list, so should be more efficient than other methods.

if your type is more generically an icollection<t>, it might help to write a short extension method if you care about performance. if not, then you'd probably get away with using linq (calling where or single).


Related Query

More Query from same tag