user1860934
user1860934

Reputation: 427

c# remove item from list without knowing index number

I have a list with collection of my object:

List<MyObj> list = new List<MyObj>();

My function received MyObj as a parameter and i want to remove this object from the list like suggest here: c# remove item from list

    private void remove(MyObj obj)
    {
        var itemToRemove = list.Where(x => x.fileName == obj.fileName);

        if (itemToRemove != null)
            list.Remove(itemToRemove);
    }

Compiler error received:

cannot convert from 'System.Collections.Generic.IEnumerable' to 'namespace.MyObj'

Upvotes: 1

Views: 649

Answers (4)

Rohit Vats
Rohit Vats

Reputation: 81243

You should use RemoveAll method exposed by list to remove all the matching elements -

private void remove(MyObj obj)
{
    var itemToRemove = list.RemoveAll(x => x.fileName == obj.fileName);
}

Upvotes: 0

Moo-Juice
Moo-Juice

Reputation: 38825

Where() returns an IEnumerable<>

Try this:

private void remove(MyObj obj)
{
    var itemToRemove = list.Where(x => x.fileName == obj.fileName);

    if (itemToRemove.Any())
        list.Remove(itemToRemove.First());
}

Better yet, as you're using List<>:

list.RemoveAll(x => x.fileName == obj.fileName);

Edit

Other solutions, that are all equally viable from the comments below. Pick your poison, though selfishly (and perhaps obviously) I prefer the readability and simplicity of the RemoveAll method:

Knittl:

list = list.Where(x => x.filename != obj.filename).ToList();

Jeroen van Langen:

var itemToRemove = list.Where(x => x.fileName == obj.fileName).FirstOfDefault(); 
if (itemToRemove != null)
    list.Remove(itemToRemove);

Upvotes: 10

Itanex
Itanex

Reputation: 1714

There is no need for you to implement this method, the remove method of List already performs this operation as expected.

http://msdn.microsoft.com/en-us/library/cd666k3e.aspx

public bool Remove(
    T item
)

Upvotes: 1

King King
King King

Reputation: 63317

You were mixed up between Where and FirstOrDefault:

private void remove(MyObj obj)
{
    var itemToRemove = list.FirstOrDefault(x => x.fileName == obj.fileName);
    if (itemToRemove != null)
        list.Remove(itemToRemove);
}

Upvotes: 3

Related Questions