Métodos de Listas
Neste capítulo, serão abordados alguns métodos úteis de listas.
Remove()
O método Remove remove a primeira ocorrência de um elemento de uma lista.
Sintaxe:
exampleList.remove(targetElement);
index.cs
123456789101112131415161718192021222324252627using 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 + " "); } } } }
Caso tal elemento não seja encontrado, nenhuma ação será realizada.
index.cs
123456789101112131415161718192021222324252627using 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()
O método RemoveAt remove um elemento em um índice específico.
Sintaxe:
exampleList.RemoveAt(index);
index.cs
123456789101112131415161718192021222324252627using 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
O método Clear remove todos os elementos de uma lista. Não recebe argumentos.
Sintaxe:
exampleList.Clear();
index.cs
123456789101112131415161718192021222324252627using 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
O método Insert insere um elemento na lista em um índice especificado.
Sintaxe:
exampleList.Insert(index, elementToInsert);
index.cs
1234567891011121314151617181920212223using 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 + " "); } } }
É possível omitir as chaves {} caso haja apenas uma única instrução dentro de uma condição if, um laço for ou um laço foreach.
index.cs
123foreach(int number in numbers) { Console.Write(number + " "); }
O trecho acima é equivalente a:
index.cs
12foreach(int number in numbers) Console.Write(number + " ");
Se já houver um elemento no índice especificado, ele será deslocado para a direita, assim como os demais elementos do array após ele, caso existam. O diagrama a seguir ilustra esse processo:
Contains()
O método Contains verifica se uma lista contém um elemento específico. Retorna um valor booleano (true ou false).
Sintaxe: exampleList.Contains(element);
index.cs
1234567891011121314using 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()
O método IndexOf retorna o índice da primeira ocorrência de um elemento em uma lista.
Sintaxe: exampleList.IndexOf(element);
index.cs
123456789101112131415using 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')); } } }
Se o elemento não existir na lista, simplesmente retorna -1:
O método indexOf é especialmente útil quando se deseja acessar um elemento pelo índice, mas não se conhece o índice. Na lista vowels, deseja-se acessar o elemento o pelo índice e alterá-lo para o O maiúsculo:
index.cs
12345678910111213141516171819using 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. O que o método Remove() faz?
2. Qual é a maneira mais rápida de verificar se uma lista contém um elemento específico?
3. Qual método é utilizado para remover todos os elementos de uma lista?
4. Qual será a saída do seguinte código?
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Awesome!
Completion rate improved to 2.04
Métodos de Listas
Deslize para mostrar o menu
Neste capítulo, serão abordados alguns métodos úteis de listas.
Remove()
O método Remove remove a primeira ocorrência de um elemento de uma lista.
Sintaxe:
exampleList.remove(targetElement);
index.cs
123456789101112131415161718192021222324252627using 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 + " "); } } } }
Caso tal elemento não seja encontrado, nenhuma ação será realizada.
index.cs
123456789101112131415161718192021222324252627using 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()
O método RemoveAt remove um elemento em um índice específico.
Sintaxe:
exampleList.RemoveAt(index);
index.cs
123456789101112131415161718192021222324252627using 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
O método Clear remove todos os elementos de uma lista. Não recebe argumentos.
Sintaxe:
exampleList.Clear();
index.cs
123456789101112131415161718192021222324252627using 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
O método Insert insere um elemento na lista em um índice especificado.
Sintaxe:
exampleList.Insert(index, elementToInsert);
index.cs
1234567891011121314151617181920212223using 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 + " "); } } }
É possível omitir as chaves {} caso haja apenas uma única instrução dentro de uma condição if, um laço for ou um laço foreach.
index.cs
123foreach(int number in numbers) { Console.Write(number + " "); }
O trecho acima é equivalente a:
index.cs
12foreach(int number in numbers) Console.Write(number + " ");
Se já houver um elemento no índice especificado, ele será deslocado para a direita, assim como os demais elementos do array após ele, caso existam. O diagrama a seguir ilustra esse processo:
Contains()
O método Contains verifica se uma lista contém um elemento específico. Retorna um valor booleano (true ou false).
Sintaxe: exampleList.Contains(element);
index.cs
1234567891011121314using 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()
O método IndexOf retorna o índice da primeira ocorrência de um elemento em uma lista.
Sintaxe: exampleList.IndexOf(element);
index.cs
123456789101112131415using 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')); } } }
Se o elemento não existir na lista, simplesmente retorna -1:
O método indexOf é especialmente útil quando se deseja acessar um elemento pelo índice, mas não se conhece o índice. Na lista vowels, deseja-se acessar o elemento o pelo índice e alterá-lo para o O maiúsculo:
index.cs
12345678910111213141516171819using 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. O que o método Remove() faz?
2. Qual é a maneira mais rápida de verificar se uma lista contém um elemento específico?
3. Qual método é utilizado para remover todos os elementos de uma lista?
4. Qual será a saída do seguinte código?
Obrigado pelo seu feedback!