Remove item from list based on condition

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

I want to remove a product where ID = 1. I am trying now:

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

and it does not work.

THANKS TO ALL

+43
c #
Jul 19 '10 at 7:28
source share
7 answers

Using linq:

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

You might even want to use SingleOrDefault() and check if the item exists at all ...

EDIT:
Since stuff is a structure, SingleOrDefault() does not return null. But it will return default (material), which will have identifier 0. When you do not have identifier 0 for your regular stuff objects, you can request this identifier:

 var stuffToRemove = prods.SingleOrDefault( s => s.ID == 1 ) if( stuffToRemove.ID != 0 ) { prods.Remove( stuffToRemove ); } 
+33
Jul 19 '10 at 7:32
source share

If your collection type is List<stuff> , then the best approach is probably the following:

 prods.RemoveAll(s => s.ID == 1) 

This is only one pass (iteration) over the list, so it should be more efficient than other methods.

If your type is more typical of ICollection<T> , this can help write a short extension method if you care about performance. If not, then you will probably be able to use LINQ (calling Where or Single ).

+113
Jul 19 '10 at 7:39
source share

If you have LINQ:

 var itemtoremove = prods.Where(item => item.ID == 1).First(); prods.Remove(itemtoremove) 
+3
Jul 19 '10 at 7:32
source share

You can only delete what you have a link to. So you have to search the whole 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; } } 
0
Jul 19 '10 at 7:31
source share

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

you cannot modify a collection in foreach as Vincent suggests

0
Jul 19 '10 at 7:33
source share

You can use Linq.

 var prod = from p in prods where p.ID != 1 select p; 
0
Jul 19 '10 at 7:37
source share
 prods.Remove(prods.Find(x => x.ID == 1)); 
0
Jul 19 '10 at 7:48
source share



All Articles