Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Métodos de Listas | Estructuras de Datos y Manejo de Archivos
C# Más Allá de lo Básico

bookMétodos de Listas

En este capítulo se revisarán algunos métodos útiles de listas.

Remove()

El método Remove elimina la primera instancia de un elemento de una lista.

Sintaxis:

exampleList.remove(targetElement);
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Banana", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Remove("Banana"); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }

En caso de que no se encuentre dicho elemento, simplemente no realiza ninguna acción.

index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Banana", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Remove("some element"); // trying to remove an unknown element Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }

RemoveAt()

El método RemoveAt elimina un elemento en un índice específico.

Sintaxis:

exampleList.RemoveAt(index);
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.RemoveAt(1); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }

Clear

El método Clear elimina todos los elementos de una lista. No recibe argumentos.

Sintaxis:

exampleList.Clear();
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Clear(); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }

Insert

El método Insert inserta un elemento en la lista en un índice especificado.

Sintaxis:

exampleList.Insert(index, elementToInsert);
index.cs

index.cs

copy
1234567891011121314151617181920212223
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<int> numbers = new List<int> { 2, 4, 6, 10, 12 }; Console.Write("Before: "); foreach (int number in numbers) Console.Write(number + " "); numbers.Insert(3, 8); Console.Write("\nAfter: "); foreach (int number in numbers) Console.Write(number + " "); } } }

Se pueden omitir las llaves {} si solo hay una instrucción dentro de una condición if, un bucle for o un bucle foreach.

index.cs

index.cs

copy
123
foreach(int number in numbers) { Console.Write(number + " "); }

El fragmento anterior es equivalente a:

index.cs

index.cs

copy
12
foreach(int number in numbers) Console.Write(number + " ");

Si ya existe un elemento en el índice especificado, este se desplaza hacia la derecha, al igual que los elementos restantes del arreglo que le siguen, en caso de haberlos. El siguiente diagrama ilustra el proceso:

Contains()

El método Contains verifica si una lista contiene un elemento específico. Devuelve un valor booleano (true o false).

Sintaxis: exampleList.Contains(element);

index.cs

index.cs

copy
1234567891011121314
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; Console.WriteLine("Contains 'o': " + vowels.Contains('o')); } } }

IndexOf()

El método IndexOf devuelve el índice de la primera aparición de un elemento en una lista.

Sintaxis: exampleList.IndexOf(element);

index.cs

index.cs

copy
123456789101112131415
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; vowels.Remove('o'); Console.WriteLine("Index of 'o': " + vowels.IndexOf('o')); } } }

Si el elemento no existe en la lista, simplemente devuelve -1:

El método indexOf es especialmente útil cuando se desea acceder a un elemento por índice pero no se conoce su índice. En vowels, se desea acceder al elemento o por índice y cambiarlo a la O mayúscula:

index.cs

index.cs

copy
12345678910111213141516171819
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; int targetIndex = vowels.IndexOf('o'); Console.WriteLine(vowels[targetIndex]); vowels[targetIndex] = 'O'; Console.WriteLine(vowels[targetIndex]); } } }

1. ¿Qué hace el método Remove()?

2. ¿Cuál es la forma más rápida de comprobar si una lista contiene un elemento específico?

3. ¿Qué método se utiliza para eliminar todos los elementos de una lista?

4. ¿Cuál será la salida del siguiente código?

question mark

¿Qué hace el método Remove()?

Select the correct answer

question mark

¿Cuál es la forma más rápida de comprobar si una lista contiene un elemento específico?

Select the correct answer

question mark

¿Qué método se utiliza para eliminar todos los elementos de una lista?

Select the correct answer

question mark

¿Cuál será la salida del siguiente código?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 3

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Awesome!

Completion rate improved to 2.04

bookMétodos de Listas

Desliza para mostrar el menú

En este capítulo se revisarán algunos métodos útiles de listas.

Remove()

El método Remove elimina la primera instancia de un elemento de una lista.

Sintaxis:

exampleList.remove(targetElement);
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Banana", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Remove("Banana"); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }

En caso de que no se encuentre dicho elemento, simplemente no realiza ninguna acción.

index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Banana", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Remove("some element"); // trying to remove an unknown element Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }

RemoveAt()

El método RemoveAt elimina un elemento en un índice específico.

Sintaxis:

exampleList.RemoveAt(index);
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.RemoveAt(1); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }

Clear

El método Clear elimina todos los elementos de una lista. No recibe argumentos.

Sintaxis:

exampleList.Clear();
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Clear(); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }

Insert

El método Insert inserta un elemento en la lista en un índice especificado.

Sintaxis:

exampleList.Insert(index, elementToInsert);
index.cs

index.cs

copy
1234567891011121314151617181920212223
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<int> numbers = new List<int> { 2, 4, 6, 10, 12 }; Console.Write("Before: "); foreach (int number in numbers) Console.Write(number + " "); numbers.Insert(3, 8); Console.Write("\nAfter: "); foreach (int number in numbers) Console.Write(number + " "); } } }

Se pueden omitir las llaves {} si solo hay una instrucción dentro de una condición if, un bucle for o un bucle foreach.

index.cs

index.cs

copy
123
foreach(int number in numbers) { Console.Write(number + " "); }

El fragmento anterior es equivalente a:

index.cs

index.cs

copy
12
foreach(int number in numbers) Console.Write(number + " ");

Si ya existe un elemento en el índice especificado, este se desplaza hacia la derecha, al igual que los elementos restantes del arreglo que le siguen, en caso de haberlos. El siguiente diagrama ilustra el proceso:

Contains()

El método Contains verifica si una lista contiene un elemento específico. Devuelve un valor booleano (true o false).

Sintaxis: exampleList.Contains(element);

index.cs

index.cs

copy
1234567891011121314
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; Console.WriteLine("Contains 'o': " + vowels.Contains('o')); } } }

IndexOf()

El método IndexOf devuelve el índice de la primera aparición de un elemento en una lista.

Sintaxis: exampleList.IndexOf(element);

index.cs

index.cs

copy
123456789101112131415
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; vowels.Remove('o'); Console.WriteLine("Index of 'o': " + vowels.IndexOf('o')); } } }

Si el elemento no existe en la lista, simplemente devuelve -1:

El método indexOf es especialmente útil cuando se desea acceder a un elemento por índice pero no se conoce su índice. En vowels, se desea acceder al elemento o por índice y cambiarlo a la O mayúscula:

index.cs

index.cs

copy
12345678910111213141516171819
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; int targetIndex = vowels.IndexOf('o'); Console.WriteLine(vowels[targetIndex]); vowels[targetIndex] = 'O'; Console.WriteLine(vowels[targetIndex]); } } }

1. ¿Qué hace el método Remove()?

2. ¿Cuál es la forma más rápida de comprobar si una lista contiene un elemento específico?

3. ¿Qué método se utiliza para eliminar todos los elementos de una lista?

4. ¿Cuál será la salida del siguiente código?

question mark

¿Qué hace el método Remove()?

Select the correct answer

question mark

¿Cuál es la forma más rápida de comprobar si una lista contiene un elemento específico?

Select the correct answer

question mark

¿Qué método se utiliza para eliminar todos los elementos de una lista?

Select the correct answer

question mark

¿Cuál será la salida del siguiente código?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 3
some-alt