Check if there is value in List

Asked

Viewed 1,595 times

1

I’m trying to make a condition, where I would check, whether in a List there is a value, 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}))

It is always valid, even if the value already exists in the list

2 answers

5


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

If you haven’t implemented IEquatable nor overwritten the method Equals the default behavior will be to check if there is an element in the list that is exactly the same as what was passed by parameter, that is, if the two variables point to the same object.

You create a new object to pass by parameter, i.e., the result at all times will be false.

Even if all the properties of one object are equal to those of another, they are not the same.

From what I’ve noticed, you just want to verify the existence of an item in the list by validating 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)) { }

Indicated reading: Difference between Any, Contains and Exists

0

I was able to solve it by changing the condition code to:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.