Removing a specific item from a list using LINQ

I have a list containing some objects and you want to use LINQ to delete a specific item, but I'm not sure how to do this.

foreach (var someobject in objectList) { if (someobject.Number == 1) // There will only one item where Number == 1. { list.remove(someobject) } } 
+7
c # linq
source share
4 answers

You cannot use foreach to remove elements at enumeration, you get an exception at runtime.

You can use List.RemoveAll :

 list.RemoveAll(x => x.Number == 1); 

or, if it’s actually not a List<T> , but any sequence, LINQ:

 list = list.Where(x => x.Number != 1).ToList(); 

If you are sure that there is only one element with this number or you want to remove one maximum element, you can either use the for loop approach suggested in another answer, or this:

 var item = list.FirstOrDefault(x => x.Number == 1); if(item ! = null) list.Remove(item); 

A link to another question that I posted suggests that you change the collection while listing in C # 4 and later. No, you can not. This applies only to new parallel collections .

+27
source share

You cannot use foreach to remove an item from a collection. This will throw an exception that will be modified in the collection.

You can execute it with

 for (int i=objectList.Count-1; i>=0 ; i--) { if (objectList[i].Number == 1) // there will only one item with Number = 1 { objectList.Remove(objectList[i]); } } 

Another case is to use Remove/RemoveAll as a Tim Schmelter show.

+2
source share

You can use the foreach loop to remove an item from the list. It is important to use break to stop the loop after deleting an element. If the loop continues after removing an item from the list, an exception will be thrown.

 foreach (var someobject in objectList) { if (someobject.Number == 1) // There will only one item where Number == 1 { objectList.remove(someobject); break; } } 

However, this will ONLY work if there is only one object that you want to delete, as in your case.

+1
source share

you can delete in the index if the value matches the criteria

 for (int i=0; i < objectList.Count; i ++) { if (objectList[i].Number == 1) // there will only one item with Number = 1 { objectList.RemoveAt[i]; } } 
-one
source share

All Articles