C# | Come verificare se un elenco contiene un elemento specificato

Metodo List.Contains(T). viene utilizzato per verificare se un elemento è nella Lista o meno. Proprietà dell'elenco:

  • È diverso dagli array. Un elenco può essere ridimensionato dinamicamente ma gli array no.
  • La classe List può accettare null come valore valido per i tipi di riferimento e consente anche elementi duplicati.
  • Se la Contare diventa uguale a Capacità quindi la capacità dell'elenco aumenta automaticamente riallocando l'array interno. Gli elementi esistenti verranno copiati nel nuovo array prima dell'aggiunta del nuovo elemento.

Sintassi:

public bool Contains (T item); 

Qui, articolo è l'oggetto che deve essere individuato nella Lista. Il valore può essere null per i tipi di riferimento. Valore di ritorno: Questo metodo ritorna VERO se l'elemento si trova nell'Elenco altrimenti restituisce Falso . Di seguito i programmi illustrano l'uso di Metodo List.Contains(T): Esempio 1:

CSharp




// C# Program to check whether the> // element is present in the List> // or not> using> System;> using> System.Collections;> using> System.Collections.Generic;> class> Geeks {> > // Main Method> > public> static> void> Main(String[] args)> > {> > // Creating an List of Integers> > List <> int> >primalista => new> List <> int> >();> > // Adding elements to List> > firstlist.Add(1);> > firstlist.Add(2);> > firstlist.Add(3);> > firstlist.Add(4);> > firstlist.Add(5);> > firstlist.Add(6);> > firstlist.Add(7);> > // Checking whether 4 is present> > // in List or not> > Console.Write(firstlist.Contains(4));> > }> }>

Produzione:

True 

Esempio 2:

CSharp




// C# Program to check whether the> // element is present in the List> // or not> using> System;> using> System.Collections;> using> System.Collections.Generic;> class> Geeks {> > // Main Method> > public> static> void> Main(String[] args)> > {> > // Creating an List of String> > List firstlist => new> List();> > // Adding elements to List> > firstlist.Add(> 'Geeks'> );> > firstlist.Add(> 'For'> );> > firstlist.Add(> 'Geeks'> );> > firstlist.Add(> 'GFG'> );> > firstlist.Add(> 'C#'> );> > firstlist.Add(> 'Tutorials'> );> > firstlist.Add(> 'techcodeview.com'> );> > // Checking whether Java is present> > // in List or not> > Console.Write(firstlist.Contains(> 'Java'> ));> > }> }>

Produzione:

False 

Complessità temporale: O(n) per il metodo Contiene

Spazio ausiliario: O(n) dove n è la dimensione dell'elenco

Riferimento: