Check if there is a value in List

1

I'm trying to make a condition where I would check if there is a value in List , so I created the following:

  private void Itens_Edit(object sender, EventArgs e)
    {
        if(editar == 1)
        {
            int a = Convert.ToInt32(gridView5.GetRowCellValue(gridView5.GetSelectedRows()[0], "ITEM"));
            int b = Convert.ToInt32(gridView5.GetRowCellValue(gridView5.GetSelectedRows()[0], "QUANTIDADE"));              

            // se o item editado, conter na lista editable, adiciona na lista edit, para fazer update
            if (List_Itens_Editable.Contains(a))
            {
                // se não existir na lista edit, adiciona se nao nao.
                if(!item_edit.Contains(new Part_edit { item = a}))
                {
                    item_edit.Add(new Part_edit { item = a, qnt = b});
                }
            }
        }
    }

However, the condition:

if(!item_edit.Contains(new Part_edit { item = a}))

Always valid, even if the value already exists in the list

    
asked by anonymous 18.05.2017 / 19:43

2 answers

5
The Contains , of course, makes use of the IEquatable implementation if the class in question implements this interface, otherwise it makes use of the Equals method of the class.

If you did not implement IEquatable and did not overwrite the Equals method, the default behavior will be to check if there is an element in the list that is exactly the same as that passed by parameter , if the two variables point to the same object.

You create a new object to pass by parameter, that is, the result will always will be false .

Even though all properties of one object are the same as those of another, they are not the same.

From what I've noticed, you just want to check for an item in the list by validating for a specific property, so you can simply change its condition to

if(!item_edit.Any(it => it.item == a)) { }

or

if(!item_edit.Exists(it => it.item == a)) { }

Reading indicated: Difference between Any, Contains and Exists

    
18.05.2017 / 19:51
0

I was able to resolve by changing the condition code to:

                if (!item_edit.Exists(x => x.item == a ))
                {
                    item_edit.Add(new Part_edit { item = a, qnt = b});
                }
    
18.05.2017 / 19:51