logo

C# | Cómo comprobar si una lista contiene un elemento específico

Lista.Contiene(T) Método se utiliza para comprobar si un elemento está en la Lista o no. Propiedades de la lista:

  • Es diferente de las matrices. Se puede cambiar el tamaño de una lista dinámicamente, pero no de las matrices.
  • La clase de lista puede aceptar nulo como valor válido para tipos de referencia y también permite elementos duplicados.
  • Si el Contar se vuelve igual a Capacidad luego, la capacidad de la Lista aumenta automáticamente al reasignar la matriz interna. Los elementos existentes se copiarán a la nueva matriz antes de agregar el nuevo elemento.

Sintaxis:



public bool Contains (T item);>

Aquí, artículo es el objeto que se ubicará en la Lista. El valor puede ser nulo para los tipos de referencia. Valor de retorno: Este método regresa Verdadero si el elemento se encuentra en la Lista, de lo contrario regresa FALSO . Los siguientes programas ilustran el uso de Lista.Contiene(T) Método: Ejemplo 1:

CSharp




que es rom



cómo saber el tamaño de la pantalla



// 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 lista =>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));> >}> }>

>

sistema operativo linux

>

Producción:

True>

Ejemplo 2:

CSharp


mvc en marco de primavera



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

>

año en que se inventó la computadora

>

Producción:

False>

Complejidad del tiempo: O(n) para el método Contiene

Espacio Auxiliar: O(n) donde n es el tamaño de la lista

Referencia: