C#中Map集合的遍歷方法有哪些

c#
小樊
91
2024-09-04 15:45:43

在C#中,Map集合通常指的是Dictionary<TKey, TValue>

  1. 使用foreach循環(huán)
Dictionary<int, string> map = new Dictionary<int, string>
{
    { 1, "one" },
    { 2, "two" },
    { 3, "three" }
};

foreach (var item in map)
{
    Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
  1. 使用KeyValuePair結(jié)構(gòu)體
Dictionary<int, string> map = new Dictionary<int, string>
{
    { 1, "one" },
    { 2, "two" },
    { 3, "three" }
};

foreach (KeyValuePair<int, string> item in map)
{
    Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
  1. 使用LINQ
Dictionary<int, string> map = new Dictionary<int, string>
{
    { 1, "one" },
    { 2, "two" },
    { 3, "three" }
};

var query = from item in map
            select new { item.Key, item.Value };

foreach (var item in query)
{
    Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
  1. 使用Keys和Values屬性
Dictionary<int, string> map = new Dictionary<int, string>
{
    { 1, "one" },
    { 2, "two" },
    { 3, "three" }
};

foreach (int key in map.Keys)
{
    Console.WriteLine($"Key: {key}, Value: {map[key]}");
}

// 或者

foreach (string value in map.Values)
{
    Console.WriteLine($"Value: {value}");
}
  1. 使用ForEach方法(需要將Dictionary轉(zhuǎn)換為L(zhǎng)ist)
Dictionary<int, string> map = new Dictionary<int, string>
{
    { 1, "one" },
    { 2, "two" },
    { 3, "three" }
};

List<KeyValuePair<int, string>> list = map.ToList();
list.ForEach(item => Console.WriteLine($"Key: {item.Key}, Value: {item.Value}"));

這些方法都可以用于遍歷C#中的Dictionary<TKey, TValue>集合。你可以根據(jù)自己的需求和編程風(fēng)格選擇合適的方法。

0