Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a specific item from a list using LINQ

Tags:

c#

linq

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)
    } 
}
like image 935
Lynct Avatar asked Nov 28 '14 20:11

Lynct


People also ask

How do I delete a record in LINQ query?

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.


1 Answers

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.

like image 187
Tim Schmelter Avatar answered Sep 28 '22 09:09

Tim Schmelter