I have a list containing some objects and want to use LINQ to remove a specific item but am not sure how to do that.
foreach (var someobject in objectList)
{
if (someobject.Number == 1) // There will only one item where Number == 1.
{
list.remove(someobject)
}
}
You can delete rows in a database by removing the corresponding LINQ to SQL objects from their table-related collection. LINQ to SQL translates your changes to the appropriate SQL DELETE commands. LINQ to SQL does not support or recognize cascade-delete operations.
You cannot use a foreach
to remove items during enumeration, you're getting an exception at runtime.
You could 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 item with that number or you want to remove one item at the maximum you can either use the for loop approach suggested in the other answer or this:
var item = list.FirstOrDefault(x => x.Number == 1);
if(item ! = null) list.Remove(item);
The link to the other question i have posted suggests that you can modify a collection during enumeration in C# 4 and later. No, you can't. That applies only to the new concurrent collections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With