Map. How can we map keys to values in a C# program? The C# language has no built-in map type. But it offers a powerful Dictionary type, which we use to map things.
With Dictionary, we must specify the key type (like "string") and the value type. With Add we map a key to a value. With TryGetValue we safely check this mapping.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Use Dictionary as a map.
var map = new Dictionary<string, string>();
// ... Add some keys and values.
map.Add("cat", "orange");
map.Add("dog", "brown");
// ... Loop over the map.
foreach (var pair in map)
{
string key = pair.Key;
string value = pair.Value;
Console.WriteLine(key + "/" + value);
}
// ... Get value at a known key.
string result = map["cat"];
Console.WriteLine(result);
// ... Use TryGetValue to safely look up a value in the map.
string mapValue;
if (map.TryGetValue("dog", out mapValue))
{
Console.WriteLine(mapValue);
}
}
}cat/orange
dog/brown
orange
brown
Select. For a map function, we want a method that applies another method to each element in a collection. The Select method, part of LINQ, is ideal for mapping elements.
Note In Python, we call map to transform each element of a list—this code uppercases each string in a list.
Note 2 In C# we call Select() from the System.Linq namespace on the array. We print each uppercase string.
pets = ["bird", "fish"]
# Apply upper method to all elements with map.
for result in map(lambda x: x.upper(), pets):
print(result)BIRD
FISHusing System;
using System.Linq;
class Program
{
static void Main()
{
string[] array = { "bird", "fish" };
var result = array.Select(x => x.ToUpper());
// Print result strings.
foreach (string value in result)
{
Console.WriteLine(value);
}
}
}BIRD
FISH
Some notes. Dictionary is an important part of C# programming. It is a map collection. Usually the best way to access it is with TryGetValue—this is safe and does not throw exceptions.
A summary. In this language, no map built-in exists. But we can access a Dictionary, or use the Select method from LINQ for all our mapping needs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 10, 2023 (edit).