C# Get value from dictionary
By FoxLearn 1/21/2025 6:48:08 AM 28
using System; using System.Collections.Generic; var studentGrades = new Dictionary<string, double>() { ["Alice"] = 85.5, ["Bob"] = 92.0, ["Charlie"] = 78.3 }; // Get grade by key using indexer var grade = studentGrades["Bob"]; Console.WriteLine($"Bob's grade: {grade}");
Output: Bob's grade: 92
Note: If the key doesn’t exist, this will throw a KeyNotFoundException
.
Get the value if the key exists
Use Dictionary.TryGetValue()
to avoid exceptions. If the key exists, it returns true
and provides the value; otherwise, it returns false
.
if (studentGrades.TryGetValue("Charlie", out double grade)) { Console.WriteLine($"Charlie's grade: {grade}"); } else { Console.WriteLine("Charlie's grade not found."); }
Output: Charlie's grade: 78.3
If the key doesn’t exist, the out
parameter remains the type’s default value (e.g., 0.0
for double
).
Use ContainsKey() and Indexer
TryGetValue()
is a shortcut, but you can also combine ContainsKey()
with the indexer:
if (studentGrades.ContainsKey("Alice")) { var grade = studentGrades["Alice"]; Console.WriteLine($"Alice's grade: {grade}"); }
Output: Alice's grade: 85.5
Get the value or default if the key doesn’t exist
To handle missing keys more elegantly, use Dictionary.GetValueOrDefault()
. It returns the value if the key exists or a default value otherwise.
// Get grade for existing student var aliceGrade = studentGrades.GetValueOrDefault("Alice"); Console.WriteLine($"Alice's grade: {aliceGrade}"); // Get grade for a non-existent student var unknownGrade = studentGrades.GetValueOrDefault("Eve", -1.0); Console.WriteLine($"Eve's grade: {unknownGrade}");
Output:
Alice's grade: 85.5 Eve's grade: -1
Get all values in the dictionary
Sometimes, you might need to process all values in the dictionary. Use Dictionary.Values
to get all values.
using System.Linq; var grades = studentGrades.Values; // Total number of grades Console.WriteLine($"Total grades: {grades.Count}"); // Count grades above 80 var countAbove80 = grades.Where(g => g > 80).Count(); Console.WriteLine($"Number of grades above 80: {countAbove80}");
Output:
Total grades: 3 Number of grades above 80: 2