跳转至

C# 字典教程

原文: https://zetcode.com/csharp/dictionary/

C# 字典教程展示了如何在 C# 中使用Dictionary集合。

C# 字典

字典,也称为关联数组,是唯一键的集合和值的集合,其中每个键都与一个值关联。 检索和添加值非常快。 字典占用更多内存,因为每个值都有一个键。

C# 字典初始化器

可以使用字面值符号初始化 C# 字典。 这些元素添加在{}括号内的分配的右侧。

Program.cs

using System;
using System.Collections.Generic;

namespace Initializers
{
    class Program
    {
        static void Main(string[] args)
        {
            var domains = new Dictionary<string, string> 
            { 
                {"sk", "Slovakia"}, 
                {"ru", "Russia"},
                {"de", "Germany"},
                {"no", "Norway"}
            };

            Console.WriteLine(domains["sk"]);

            var days = new Dictionary<string, string> 
            { 
                ["mo"] =  "Monday", 
                ["tu"] =  "Tuesday", 
                ["we"] =  "Wednesday", 
                ["th"] =  "Thursday", 
                ["fr"] =  "Friday", 
                ["sa"] =  "Saturday", 
                ["su"] =  "Sunday"
            };

            Console.WriteLine(days["fr"]);
        }
    }
}

在示例中,我们使用字面值符号创建两个字典。

var domains = new Dictionary<string, string> 
{ 
    {"sk", "Slovakia"}, 
    {"ru", "Russia"},
    {"de", "Germany"},
    {"no", "Norway"}
};

创建一个新的字典。 在尖括号<>之间,我们指定键和值的数据类型。 新的键/值元素对写在嵌套的{}括号内; 每对之间用逗号分隔。 例如,"sk"键引用"Slovakia"值。

Console.WriteLine(domains["sk"]);

要获得一个值,我们指定字典名称,后跟方括号[]。 在方括号之间,我们指定键名称。

var days = new Dictionary<string, string> 
{ 
    ["mo"] =  "Monday", 
    ["tu"] =  "Tuesday", 
    ["we"] =  "Wednesday", 
    ["th"] =  "Thursday", 
    ["fr"] =  "Friday", 
    ["sa"] =  "Saturday", 
    ["su"] =  "Sunday"
};

这是替代的 C# 字典初始化器。 使用字典访问符号将值分配给键。

$ dotnet run
Slovakia
Friday

这是输出。

C# 计数元素

通过Count属性,我们可以获得字典中的键数。

Program.cs

using System;
using System.Collections.Generic;

namespace Counting
{
    class Program
    {
        static void Main(string[] args)
        {
            var domains = new Dictionary<string, string> 
            { 
                {"sk", "Slovakia"}, 
                {"ru", "Russia"},
                {"de", "Germany"},
                {"no", "Norway"}
            };

            domains.Add("pl", "Poland");

            Console.WriteLine($"There are {domains.Count} items in the dictionary");
        }
    }
}

该示例计算字典中的项目数。

Console.WriteLine($"There are {domains.Count} items in the dictionary");

在这里,我们打印字典中的项目数。

$ dotnet run
There are 5 items in the dictionary

This is the output.

C# 添加和删除元素

创建字典后,可以在字典中添加或删除新元素。

Program.cs

using System;
using System.Collections.Generic;

namespace AddRemove
{
    class Program
    {
        static void Main(string[] args)
        {
            var users = new Dictionary<string, int>()
            {
                { "John Doe", 41 },
                { "Jane Doe", 38 },
                { "Lucy Brown", 29 },
            };

            users["Paul Brown"] = 33;
            users.Add("Thomas Pattison", 34);

            Console.WriteLine(string.Join(", ", users));

            users.Remove("Jane Doe");

            Console.WriteLine(string.Join(", ", users));

            users.Clear();

            if (users.Count == 0) 
            {
                Console.WriteLine("The users dictionary is empty");
            }
        }
    }
}    

该示例创建一个新词典并使用几种内置方法对其进行修改。

var users = new Dictionary<string, int>()
{
    { "John Doe", 41 },
    { "Jane Doe", 38 },
    { "Lucy Brown", 29 },
};

创建一个新的字典。 用户名是键,用户年龄是值。

users["Paul Brown"] = 33;
users.Add("Thomas Pattison", 34);

我们使用字典访问符号和Add()方法将两个新对添加到字典中。

Console.WriteLine(string.Join(", ", users));

我们使用字符串Join()方法一次显示所有元素。

users.Remove("Jane Doe");

使用Remove()方法删除一对。 该参数是字典键。

users.Clear();

Clear()方法清除字典。

$ dotnet run
[John Doe, 41], [Jane Doe, 38], [Lucy Brown, 29], [Paul Brown, 33], [Thomas Pattison, 34]
[John Doe, 41], [Lucy Brown, 29], [Paul Brown, 33], [Thomas Pattison, 34]
The users dictionary is empty

This is the output.

C# ContainsKeyContainsValue方法

ContainsKey()方法确定字典是否包含指定的键,ContainsValue()方法确定字典是否包含指定的值。

Program.cs

using System;
using System.Collections.Generic;

namespace CheckElements
{
    class Program
    {
        static void Main(string[] args)
        {
            var domains = new Dictionary<string, string>
            {
                {"sk", "Slovakia"},
                {"ru", "Russia"},
                {"de", "Germany"},
                {"no", "Norway"}
            };

            var key = "sk";

            if (domains.ContainsKey(key))
            {
                Console.WriteLine($"The {key} key is in the dictionary");
            } else 
            {
                Console.WriteLine($"The {key} key is in not the dictionary");
            }

            var value = "Slovakia";

            if (domains.ContainsValue(value))
            {
                Console.WriteLine($"The {value} value is in the dictionary");
            } else 
            {
                Console.WriteLine($"The {value} value is in not the dictionary");
            }
        }
    }
}

在示例中,我们检查字典中是否存在"sk"键和"Slovakia"值。

$ dotnet run
The sk key is in the dictionary
The Slovakia value is in the dictionary

This is the output.

C# 遍历字典

有几种遍历 C# 字典的方法。

Program.cs

using System;
using System.Collections.Generic;

namespace Traversing
{
    class Program
    {
        static void Main(string[] args)
        {
            var domains = new Dictionary<string, string> {
                {"sk", "Slovakia"},
                {"ru", "Russia"},
                {"de", "Germany"},
                {"no", "Norway"}
            };

            foreach (var (key, value) in domains)
            {
                Console.WriteLine($"{key}: {value}");
            }

            Console.WriteLine("**************************************");

            foreach (var kvp in domains)
            {
                Console.WriteLine($"{kvp.Key}: {kvp.Value}");
            }

            Console.WriteLine("**************************************");

            // oldschool
            foreach (KeyValuePair<string, string> entry in domains)
            {
                Console.WriteLine($"{entry.Key}: {entry.Value}");
            }
        }
    }
}

该示例使用foreach遍历字典。

foreach (var (key, value) in domains)
{
    Console.WriteLine($"{key}: {value}");
}

在此foreach循环中,我们成对浏览字典。 每对都分解为其键和值。

foreach (var kvp in domains)
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

在这种情况下,我们通过KeyValue属性访问键和值。

// oldschool
foreach (KeyValuePair<string, string> entry in domains)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

最后,这是一种使用KeyValuePair成对遍历字典的较旧方法。

$ dotnet run
sk: Slovakia
ru: Russia
de: Germany
no: Norway
**************************************
sk: Slovakia
ru: Russia
de: Germany
no: Norway
**************************************
sk: Slovakia
ru: Russia
de: Germany
no: Norway

This is the output.

C# 允许分别循环遍历键和值。

Program.cs

using System;
using System.Collections.Generic;

namespace Traversing2
{
    class Program
    {
        static void Main(string[] args)
        {
            var domains = new Dictionary<string, string> 
            {
                {"sk", "Slovakia"},
                {"ru", "Russia"},
                {"de", "Germany"},
                {"no", "Norway"}
            };

            Console.WriteLine("Keys:");

            foreach (var val in domains.Keys)
            {
                Console.WriteLine(val);
            }

            Console.WriteLine("\nValues:");

            foreach (var val in domains.Values)
            {
                Console.WriteLine(val);
            }
        }
    }
}

该示例在两个foreach循环中打印字典的所有键和所有值。

foreach (var val in domains.Keys)
{
    Console.WriteLine(val);
}

我们使用Keys属性获取所有键。

foreach (var val in domains.Values)
{
    Console.WriteLine(val);
}

我们使用Values属性获取所有值。

$ dotnet run
Keys:
sk
ru
de
no

Values:
Slovakia
Russia
Germany
Norway

This is the output.

C# 排序字典

我们可以使用 LINQ 对字典进行排序。

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;

namespace Sorting
{
    class Program
    {
        static void Main(string[] args)
        {
            var users = new Dictionary<string, int>()
            {
                { "John", 41 },
                { "Jane", 38 },
                { "Lucy", 29 },
                { "Paul", 24 }
            };

            var sortedUsersByValue = users.OrderBy(user => user.Value);

            foreach (var user in sortedUsersByValue)
            {
                Console.WriteLine($"{user.Key} is {user.Value} years old");
            }
        }
    }
}

该示例按用户年龄对字典进行排序。

var sortedUsersByValue = users.OrderBy(user => user.Value);

OrderBy()方法用于按条目的值对条目进行排序。

$ dotnet run
Paul is 24 years old
Lucy is 29 years old
Jane is 38 years old
John is 41 years old

输出按字典值排序。

C# SortedDictionary

SortedDictionary表示按键排序的键/值对的集合。

Program.cs

using System;
using System.Collections.Generic;

namespace SortedDictEx
{
    class Program
    {
        static void Main(string[] args)
        {
            var sortedUsers = new SortedDictionary<string, int>()
            {
                { "John", 41 },
                { "Jane", 38 },
                { "Lucy", 29 },
                { "Paul", 24 }
            };

            foreach (var user in sortedUsers)
            {
                Console.WriteLine($"{user.Key} is {user.Value} years old");
            }
        }
    }
}

该示例演示了SortedDictionary的用法。

$ dotnet run
Jane is 38 years old
John is 41 years old
Lucy is 29 years old
Paul is 24 years old

输出按字典键排序。

在本教程中,我们使用了 C# 词典集合。

您可能也对以下相关教程感兴趣: MySQL C# 教程C# 中的日期和时间用 C# 阅读网页C# Winforms 教程


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组