Search code examples
c#.netentity-frameworklinq

Remove item from list based on condition


I have a struct like this:

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

and want to to remove the product where ID is 1.
I'm trying this currently:

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

and it's not working.

THANKS TO ALL


Solution

  • 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 );
    }