0

I have a List<Fill> items

Here is the Fill class :

public class Fill
{
    public string arret { get; set;}
    public string ligneSens { get; set;}
}

How can I remove an item from this List using the string value arret and ligneSens ?

Example :

void OnDelete(object sender, EventArgs e, string arretName, string ligneSensName)
{
    var aFill = new Fill
    {
        arret = arretName,
        ligneSens = ligneSensName
    };

    items.Remove(aFill); //<--- this doesn't work
}

Sorry for the title of the post I didn't know how to ask that.

D.Costa
  • 159
  • 1
  • 1
  • 10

3 Answers3

6

You should override the Equals and GetHashCode methods of object. When you call the Remove on a reference type (classes) then it will look for one by it's Equals method.

public class Fill
{
    public string arret { get; set; }
    public string ligneSens { get; set; }

    public override bool Equals(object obj)
    {
        var other = obj as Fill;
        if(other == null)
            return false;

        return other.arret == arret && other.ligneSens == ligneSens;
    }

    public override int GetHashCode()
    {
        return arret.GetHashCode() ^
               ligneSens.GetHashcode();
    }
}

For what are the best practices on GetHashCode() overriding search online, there are many questions about it

Another way, is to specifically say what to remove by passing a predicate to evaluate for each item in the collection:

items.RemoveAll(item => item.arret = arretName &&  
                        item.ligneSens == ligneSensName);
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
4

You have to use RemoveAll() for that, currently you are passing a newly created object, about which items does not have information, because it is a new reference not the same reference :

void OnDelete(object sender, EventArgs e, string arretName, string ligneSensName)
{
   items.RemoveAll(item => item.arret == arretName &&  item.ligneSens == ligneSensName);
}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
2

Use List API RemoveAll

items.RemoveAll(x => x.arret.Equals("value") && x.ligneSensName.Equals("ligneValue"));

Anonymous Duck
  • 2,942
  • 1
  • 12
  • 35
  • 5
    Just to be precise: `RemoveAll` has nothing to do with LINQ, it's an instance method of `List`. LINQ has a functional approach and does not change existing collections or their elements. – René Vogt Aug 08 '16 at 10:04
  • @RenéVogt thanks for pointing it out, I'm used to term api's using lamba expression as LINQ – Anonymous Duck Aug 08 '16 at 10:05