tags:

views:

86

answers:

7
public struct stuff
{
    public int ID;
    public int quan;
}

I want to to remove a product where ID = 1. I'm trying this currently:

prods.Remove(new stuff{ prodID = 1});

and it's not working.

THANKS TO ALL

A: 

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;
    }
}
Vincent McNabb
isn't it faster to use the find or findIndex function on a list instead of looping through it?
Rob
You can't modify the collection you are iterating
Graphain
@Rob, for a List, find should be the same.
Graphain
@Graphain oops.@Rob, yes a find is probably better.
Vincent McNabb
+3  A: 

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 );
}
tanascius
Pretty sure Remove(null) throws an exception which rules out SingleOrDefault where it is.
Graphain
@Graphain: I added an example for you
tanascius
A: 

If you have LINQ:

var itemtoremove = prods.Where(item => item.ID == 1).First();
prods.Remove(itemtoremove)
Nathan W
You can put your `where` query as a parameter to First()
Graphain
A: 

prods.Remove(prods.Single(p=>p.ID == 1));

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

Kikaimaru
Single would be slower than first but it does guarantee you don't have duplicate products for the same ID which may be something you want to check for.
Graphain
A: 

You could use Linq.

var prod = from p in prods
           where p.ID != 1
           select p;
Chris
This won't remove the object. If you assign like `prods = prods.Where(p != 1).ToList()` you're closer, but that won't modify a list you've been given as a parameter.
Graphain
+4  A: 

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).

Noldorin
A: 
prods.Remove(prods.Find(x => x.ID == 1));
Alex