0% found this document useful (0 votes)
2 views

C# Dictionary Methods Guide

C# dictionaries are collections that store unique key-value pairs and are part of the System.Collections.Generic namespace. Common methods include Add, ContainsKey, ContainsValue, Remove, TryGetValue, and Clear, which facilitate various operations such as adding, checking, and removing elements. Key characteristics include fast lookups and the requirement for unique keys, making them efficient for data storage and retrieval.

Uploaded by

gabbhy2704
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C# Dictionary Methods Guide

C# dictionaries are collections that store unique key-value pairs and are part of the System.Collections.Generic namespace. Common methods include Add, ContainsKey, ContainsValue, Remove, TryGetValue, and Clear, which facilitate various operations such as adding, checking, and removing elements. Key characteristics include fast lookups and the requirement for unique keys, making them efficient for data storage and retrieval.

Uploaded by

gabbhy2704
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

C# Dictionary Methods Guide

can you tell me about c# dictionaries and some common methods for c# dictionaries? basically
everything I need to know as a beginner

C# Dictionaries Overview

A dictionary in C# is a collection type that stores key-value pairs. It's part of the
System.Collections.Generic namespace. Each key in a dictionary must be unique, and each key is
associated with a value.

Namespace: `System.Collections.Generic`
Class: `Dictionary<TKey, TValue>`

Key Characteristics

1. Unique Keys: Each key must be unique.


2. Fast Lookup: Provides fast access to values based on keys (using a hash table).
3. Generic: You define the types of the keys (`TKey`) and values (`TValue`) when creating the
dictionary.

Creating a Dictionary

csharp

using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
// Create a dictionary
Dictionary<int, string> students = new Dictionary<int, string>();

// Adding key-value pairs


students.Add(1, "Alice");
students.Add(2, "Bob");
students.Add(3, "Charlie");

// Accessing values
Console.WriteLine(students[1]); // Output: Alice
}
}

Common Methods for Dictionaries

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/4
Here’s a list of some commonly used methods and properties:

1. Add(Key, Value)

Adds a key-value pair to the dictionary.


Throws an exception if the key already exists.

csharp

dictionary.Add(4, "David");

2. ContainsKey(Key)

Checks if a specific key exists in the dictionary.

csharp

bool hasKey = dictionary.ContainsKey(2); // true

3. ContainsValue(Value)

Checks if a specific value exists in the dictionary.

csharp

bool hasValue = dictionary.ContainsValue("Bob"); // true

4. Remove(Key)

Removes the key-value pair with the specified key.

csharp

dictionary.Remove(3);

5. TryGetValue(Key, out Value)

Tries to get the value associated with the key. If the key exists, returns true and assigns the value to
`out`. Otherwise, returns false.

csharp

if (dictionary.TryGetValue(1, out string value))


{

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/4
Console.WriteLine(value); // Output: Alice
}

6. Count

Gets the number of key-value pairs in the dictionary.

csharp

int count = dictionary.Count;

7. Keys and Values

Retrieves all keys or values.

csharp

foreach (int key in dictionary.Keys)


{
Console.WriteLine(key);
}

foreach (string value in dictionary.Values)


{
Console.WriteLine(value);
}

8. Clear()

Removes all elements from the dictionary.

csharp

dictionary.Clear();

Iterating Through a Dictionary

You can iterate through key-value pairs using a `foreach` loop.

csharp

foreach (KeyValuePair<int, string> kvp in dictionary)


{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}

Example: Practical Usage


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/4
csharp

using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
// Create and populate dictionary
Dictionary<string, int> inventory = new Dictionary<string, int>
{
{ "Apples", 10 },
{ "Oranges", 5 },
{ "Bananas", 20 }
};

// Check if a key exists


if (inventory.ContainsKey("Apples"))
{
Console.WriteLine($"Apples: {inventory["Apples"]}");
}

// Update value
inventory["Oranges"] += 5;

// Remove an item
inventory.Remove("Bananas");

// Display inventory
foreach (var item in inventory)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
}

Output:

makefile

Apples: 10
Apples: 10
Oranges: 10

Things to Keep in Mind

1. Key Equality: The type of the key must implement a proper equality comparison (usually
`Equals()` and `GetHashCode()`).
2. Exceptions: Adding a duplicate key with `Add()` throws an exception. Use `TryAdd()` or
`ContainsKey()` to avoid this.
3. Default Values: Accessing a non-existent key with `dictionary[key]` throws a
`KeyNotFoundException`. Use `TryGetValue()` instead.

Let me know if you'd like examples or explanations of any specific part in more depth!

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/4

You might also like