Blog Details

C#中遍历Dictionary字典的几种方式

在C#中,Dictionary 是一个常用的集合类型,用于存储键值对。你可以通过多种方式遍历 Dictionary,以下是一些常见的方法:

文章目录

1. 使用 `foreach` 循环遍历键值对2. 使用 `foreach` 循环遍历键或值3. 使用 `foreach` 循环和 `Enumerator`4. 使用 LINQ 查询

1. 使用 foreach 循环遍历键值对

using System;

using System.Collections.Generic;

class Program

{

static void Main()

{

Dictionary dictionary = new Dictionary

{

{ 1, "One" },

{ 2, "Two" },

{ 3, "Three" }

};

foreach (KeyValuePair kvp in dictionary)

{

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

}

}

}

2. 使用 foreach 循环遍历键或值

如果你只需要遍历键或值,可以使用 Dictionary 的 Keys 或 Values 属性。

using System;

using System.Collections.Generic;

class Program

{

static void Main()

{

Dictionary dictionary = new Dictionary

{

{ 1, "One" },

{ 2, "Two" },

{ 3, "Three" }

};

// 遍历键

foreach (int key in dictionary.Keys)

{

Console.WriteLine($"Key = {key}");

}

// 遍历值

foreach (string value in dictionary.Values)

{

Console.WriteLine($"Value = {value}");

}

}

}

3. 使用 foreach 循环和 Enumerator

虽然不常用,但你也可以使用 Dictionary.Enumerator 进行遍历。

using System;

using System.Collections.Generic;

class Program

{

static void Main()

{

Dictionary dictionary = new Dictionary

{

{ 1, "One" },

{ 2, "Two" },

{ 3, "Three" }

};

Dictionary.Enumerator enumerator = dictionary.GetEnumerator();

while (enumerator.MoveNext())

{

KeyValuePair kvp = enumerator.Current;

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

}

// 完成后记得释放枚举器

enumerator.Dispose();

}

}

4. 使用 LINQ 查询

你也可以使用 LINQ(Language Integrated Query)来查询和遍历 Dictionary。

using System;

using System.Collections.Generic;

using System.Linq;

class Program

{

static void Main()

{

Dictionary dictionary = new Dictionary

{

{ 1, "One" },

{ 2, "Two" },

{ 3, "Three" }

};

var query = from kvp in dictionary

select new { kvp.Key, kvp.Value };

foreach (var item in query)

{

Console.WriteLine($"Key = {item.Key}, Value = {item.Value}");

}

}

}

这些方法提供了灵活的方式来遍历 Dictionary,根据你的具体需求选择最适合的方法。