C# | Com comprovar si una llista conté un element especificat

Mètode List.Contains(T). s'utilitza per comprovar si un element és a la llista o no. Propietats de la llista:

  • És diferent de les matrius. Una llista es pot canviar de mida dinàmicament però les matrius no.
  • La classe de llista pot acceptar null com a valor vàlid per als tipus de referència i també permet elements duplicats.
  • Si el Compte esdevé igual a Capacitat aleshores la capacitat de la llista augmenta automàticament mitjançant la reassignació de la matriu interna. Els elements existents es copiaran a la nova matriu abans d'afegir l'element nou.

Sintaxi:

public bool Contains (T item); 

Aquí, article és l'objecte que s'ha de localitzar a la llista. El valor pot ser nul per als tipus de referència. Valor de retorn: Aquest mètode torna És cert si l'element es troba a la llista, en cas contrari retorna Fals . Els programes següents il·lustren l'ús de Mètode List.Contains(T): Exemple 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> >primera llista => 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));> > }> }>

Sortida:

True 

Exemple 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'> ));> > }> }>

Sortida:

False 

Complexitat temporal: O(n) per al mètode Conté

Espai auxiliar: O(n) on n és la mida de la llista

Referència: