How to check if an item has already been entered in a list in c#

Asked

Viewed 532 times

-3

  1. There is the list classes
  2. Inside that list I put objects like gang
  3. Each object has (string)nameTurma.Text & a numerical value (int)numericUpDown1.Value
  4. I use the method addTurma to place objects in the list classes

        public static List<turma> turmas = new List<turma>();
    
        public static void addTurma(turma x)
        {
    
            turmas.Add(x);
    
        }
     turma x = new turma(nomeTurma.Text,(int)numericUpDown1.Value);
     //Se nomeTurma.Text não exite na lista turmas
      {
      turma.addTurma(x);
      }
    

I just want to add class objects which do not have the same name, that is, check whether (string)nameTurma.Text already exists on the list classes

  • 1

    Make a go on the list and see if it exists by comparing the two, see if there is an equal and controls with a bool

  • @Brunoh. There is no other way, there is no kind of a method that already does this own of the lists ?

  • 2

    Yeah, use the . Any().

  • @Francis as I use the . Any ?

  • @Amadeuantunes Linq for me is equal to regex, I know how it works, but I have no idea how you use kkkkkk Anyway, you can see in the documentation and maybe find the expression you need to do this check: https://msdn.microsoft.com/pt-br/library/bb534972(v=vs.110). aspx

  • 2

    It’s gonna be something like this: bool existeNome = turmas.Any(p => p.Nome == nomeTurma.Text);

  • 1

    You can also make a If if no you add, type:if(!turmas.Any(p => p.Nome == nomeTurma.Text){...})

  • https://stackoverflow.com/questions/45400646/how-to-check-if-item-already-is-in-list-c-sharp/45400737#45400737 helped me so

  • The question is already open ^^

Show 4 more comments

1 answer

2


if(turmas.Any(t => t.Text == text))  
{

}

Browser other questions tagged

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