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

   2024-09-30 9000
核心提示:在C#中,Map集合通常指的是DictionaryTKey, TValue使用foreach循环:Dictionaryint, string map = new Dictionaryint, string{{

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

使用foreach循环
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}");}
使用KeyValuePair结构体
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}");}
使用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}");}
使用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}");}
使用ForEach方法(需要将Dictionary转换为List)
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>集合。你可以根据自己的需求和编程风格选择合适的方法。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号