Earn More by Sharing What You Love
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Tim Corey
10m 19s
Uma estrutura de dados poderosa em C# que muitas vezes é subutilizada é o dicionário. A classe Dictionary é uma coleção genérica encontrada no namespace System.Collections.Generic. Em seu vídeo " A estrutura de dados Dictionary em C# em 10 minutos ou menos ", Tim Corey oferece um guia conciso e prático sobre como usar dicionários de forma eficaz em suas aplicações C#. Este artigo detalha as explicações e exemplos de Tim, com o objetivo de ajudá-lo a compreender os fundamentos do dicionário C# com facilidade.
Tim começa apresentando o conceito de dicionário em C#. Ele compara isso a um dicionário da vida real, onde você procura uma palavra (chave) para encontrar sua definição (valor). Em C#, um dicionário é uma coleção de pares chave-valor onde cada chave é única e não pode ser nula.
Um dicionário em C# é declarado usando a sintaxe Dictionary<TKey, TValue>, permitindo armazenamento e recuperação de dados eficiente através de pares chave-valor. Com uma capacidade inicial padrão definida durante sua criação, os dicionários podem se ajustar dinamicamente à medida que elementos são adicionados.
Em (0:28), Tim começa com um aplicativo de console básico para demonstrar como criar um dicionário. Ele usa o seguinte código para inicializar um dicionário com números inteiros como chaves e strings como valores:
// Declare a dictionary with integer keys and string values
Dictionary<int, string> rookieOfTheYear = new Dictionary<int, string>();' Declare a dictionary with integer keys and string values
Dim rookieOfTheYear As New Dictionary(Of Integer, String)()' Declare a dictionary with integer keys and string values
Dim rookieOfTheYear As New Dictionary(Of Integer, String)()Aqui, Dictionary<int, string> especifica que as chaves serão inteiros (int) e os valores serão strings (string). A variável rookieOfTheYear é o nome da instância do dicionário. Você também pode usar chaves do tipo string definindo o tipo da chave como string.
Tim agora adiciona elementos ao dicionário em (2:08). Ele mostra como usar o método Add para adicionar pares chave-valor:
// Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller");
rookieOfTheYear.Add(2001, "Jane Doe");
rookieOfTheYear.Add(2002, "Jane Doe");
rookieOfTheYear.Add(2003, "John Smith");// Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller");
rookieOfTheYear.Add(2001, "Jane Doe");
rookieOfTheYear.Add(2002, "Jane Doe");
rookieOfTheYear.Add(2003, "John Smith");' Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller")
rookieOfTheYear.Add(2001, "Jane Doe")
rookieOfTheYear.Add(2002, "Jane Doe")
rookieOfTheYear.Add(2003, "John Smith")' Add entries to the dictionary
rookieOfTheYear.Add(2000, "Mike Miller")
rookieOfTheYear.Add(2001, "Jane Doe")
rookieOfTheYear.Add(2002, "Jane Doe")
rookieOfTheYear.Add(2003, "John Smith")Neste exemplo:
rookieOfTheYear.Add(2000, "Mike Miller") adiciona a chave especificada 2000 com o valor "Mike Miller".
Da mesma forma, as chaves 2001, 2002, e 2003 são associadas a "Jane Doe", "Jane Doe", e "John Smith" respectivamente.
Ele observa que, embora os valores possam ser repetidos, as chaves devem ser únicas. A tentativa de adicionar uma chave duplicada resulta em uma exceção:
rookieOfTheYear.Add(2001, "Jane Doe"); // This will throw an exceptionrookieOfTheYear.Add(2001, "Jane Doe"); // This will throw an exceptionrookieOfTheYear.Add(2001, "Jane Doe") ' This will throw an exceptionrookieOfTheYear.Add(2001, "Jane Doe") ' This will throw an exceptionEsta exceção ocorre porque a chave 2001 já existe no dicionário.
Para demonstrar a recuperação de valores, Tim usa a seguinte linha de código em (3:45):
// Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear[2002]); // Outputs: Jane Doe// Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear[2002]); // Outputs: Jane Doe' Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear(2002)) ' Outputs: Jane Doe' Accessing a value with a specific key
Console.WriteLine(rookieOfTheYear(2002)) ' Outputs: Jane DoeAqui, rookieOfTheYear[2002] acessa o valor associado à chave 2002. Essa é uma maneira muito eficiente de buscar valores com base em chaves.

Em (4:29), Tim discute como verificar se uma chave existe no dicionário usando o método ContainsKey:
// Check if a key exists before accessing its value
if (rookieOfTheYear.ContainsKey(2002))
{
Console.WriteLine(rookieOfTheYear[2002]);
}// Check if a key exists before accessing its value
if (rookieOfTheYear.ContainsKey(2002))
{
Console.WriteLine(rookieOfTheYear[2002]);
}' Check if a key exists before accessing its value
If rookieOfTheYear.ContainsKey(2002) Then
Console.WriteLine(rookieOfTheYear(2002))
End If' Check if a key exists before accessing its value
If rookieOfTheYear.ContainsKey(2002) Then
Console.WriteLine(rookieOfTheYear(2002))
End IfNo exemplo acima, ContainsKey(2002) verifica se a chave 2002 existe no dicionário. Se existir, o valor correspondente ("Jane Doe") é impresso.
Se a chave não existir, o dicionário não retorna nenhum resultado, evitando erros ao acessar chaves inexistentes.
Tim aprofunda as funcionalidades do dicionário em (5:33), criando um exemplo mais complexo com um dicionário que mapeia strings para listas de strings:
// Declare a dictionary with string keys and List<string> as values
Dictionary<string, List<string>> wishList = new();
// Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", new List<string> { "Xbox", "Tesla", "Pizza" });
wishList.Add("Billy Bob", new List<string> { "PS5", "Ford", "Hoagie" });
wishList.Add("Mary Jane", new List<string> { "House", "Car", "Sub" });// Declare a dictionary with string keys and List<string> as values
Dictionary<string, List<string>> wishList = new();
// Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", new List<string> { "Xbox", "Tesla", "Pizza" });
wishList.Add("Billy Bob", new List<string> { "PS5", "Ford", "Hoagie" });
wishList.Add("Mary Jane", new List<string> { "House", "Car", "Sub" });' Declare a dictionary with string keys and List(Of String) as values
Dim wishList As New Dictionary(Of String, List(Of String))()
' Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", New List(Of String) From {"Xbox", "Tesla", "Pizza"})
wishList.Add("Billy Bob", New List(Of String) From {"PS5", "Ford", "Hoagie"})
wishList.Add("Mary Jane", New List(Of String) From {"House", "Car", "Sub"})' Declare a dictionary with string keys and List(Of String) as values
Dim wishList As New Dictionary(Of String, List(Of String))()
' Add entries to the dictionary with lists as values
wishList.Add("Tim Corey", New List(Of String) From {"Xbox", "Tesla", "Pizza"})
wishList.Add("Billy Bob", New List(Of String) From {"PS5", "Ford", "Hoagie"})
wishList.Add("Mary Jane", New List(Of String) From {"House", "Car", "Sub"})Aqui:
As teclas são sequências de caracteres (ex.: "Tim Corey", "Billy Bob", "Mary Jane").
Os valores são listas de strings, representando uma lista de desejos para cada pessoa.
Em (7:24), Tim demonstra como iterar sobre um dicionário usando um loop foreach:
// Iterate over each key-value pair in the dictionary
foreach (var (key, value) in wishList)
{
Console.WriteLine($"{key}'s wish list:");
// Iterate over each item in the list of values
foreach (var item in value)
{
Console.WriteLine($"\t{item}");
}
}// Iterate over each key-value pair in the dictionary
foreach (var (key, value) in wishList)
{
Console.WriteLine($"{key}'s wish list:");
// Iterate over each item in the list of values
foreach (var item in value)
{
Console.WriteLine($"\t{item}");
}
}' Iterate over each key-value pair in the dictionary
For Each kvp In wishList
Dim key = kvp.Key
Dim value = kvp.Value
Console.WriteLine($"{key}'s wish list:")
' Iterate over each item in the list of values
For Each item In value
Console.WriteLine(vbTab & item)
Next
Next' Iterate over each key-value pair in the dictionary
For Each kvp In wishList
Dim key = kvp.Key
Dim value = kvp.Value
Console.WriteLine($"{key}'s wish list:")
' Iterate over each item in the list of values
For Each item In value
Console.WriteLine(vbTab & item)
Next
NextNeste exemplo:
foreach (var (key, value) in wishList) itera sobre cada par chave-valor no dicionário wishList.
key refere-se à chave (por exemplo, "Tim Corey").
value refere-se à lista de valores associados a essa chave.
O laço interno itera sobre cada item da lista e o imprime.
Isso permite imprimir todos os elementos usando um loop para acessar os elementos do dicionário um por um, com uma chave específica e seu respectivo valor também específico. Aqui está o resultado:

Tim também mostra como acessar valores mais complexos no dicionário usando explicitamente o índice especificado em (8:26):
// Access the first item in the list of values for the specified key
Console.WriteLine(wishList["Tim Corey"][0]); // Outputs: Xbox// Access the first item in the list of values for the specified key
Console.WriteLine(wishList["Tim Corey"][0]); // Outputs: Xbox' Access the first item in the list of values for the specified key
Console.WriteLine(wishList("Tim Corey")(0)) ' Outputs: Xbox' Access the first item in the list of values for the specified key
Console.WriteLine(wishList("Tim Corey")(0)) ' Outputs: XboxAqui, wishList["Tim Corey"] acessa a lista associada à chave "Tim Corey", e [0] recupera o primeiro item dessa lista.
Tim conclui em (9:00) enfatizando a importância de compreender os dicionários. Ele destaca que, embora os dicionários possam não ser usados com frequência, são incrivelmente úteis em cenários que exigem chaves exclusivas e pesquisas eficientes.
Criação de dicionários: Compreenda como inicializar dicionários com vários tipos de dados.
Adicionando Elementos: Aprenda a importância de chaves únicas e como lidar com exceções de chaves duplicadas.
Acesso a valores: Recupere valores de forma eficiente usando chaves.
Verificação da existência da chave: Evite erros verificando a existência da chave antes de acessar os valores.
Uso avançado: Implemente dicionários mais complexos, como aqueles com listas como valores.
Iteração: Utilize loops para acessar e exibir todos os elementos de um dicionário.
Seguindo o vídeo de Tim Corey, você poderá dominar o uso de dicionários em C#, aprimorando seu conjunto de ferramentas de programação para cenários que exigem recuperação e armazenamento de dados eficientes. Confira o canal do Tim para mais vídeos informativos sobre C#.
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Join our newsletter, you’ll get exclusive access on article updates. We value your privacy