Convert a Dictionary to a List of KeyValuePair in C#

原文地址:https://www.techiedelight.com/convert-a-dictionary-to-a-list-of-keyvaluepair-in-csharp/

1. Using Dictionary<TKey,TValue>.ToList() Method

A simple solution is to use ToList() method to create a List<KeyValuePair> from a Dictionary<TKey,TValue>. It is available in LINQ and you need to add System.Linq namespace.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Linq;
using System.Collections.Generic;
 
public class Example
{
    public static void Main()
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();
 
        dict.Add("White", "#FFFFFF");
        dict.Add("Grey", "#808080");
        dict.Add("Silver", "#C0C0C0");
        dict.Add("Black", "#000000");
 
        List<KeyValuePair<string, string>> mappings = dict.ToList();
 
        Console.WriteLine(String.Join(", ", mappings));
    }
}
Download  Run Code

Output:

[White, #FFFFFF], [Grey, #808080], [Silver, #C0C0C0], [Black, #000000]

2. Using foreach loop

Another option is to create a new list of KeyValuePair, iterate over the Dictionary<TKey,TValue>, and manually add each KeyValuePair to the new dictionary. This can be easily done using the foreach loop, as demonstrated below. Note that this doesn’t uses LINQ.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collections.Generic;
 
public class Example
{
    public static void Main()
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();
 
        dict.Add("White", "#FFFFFF");
        dict.Add("Grey", "#808080");
        dict.Add("Silver", "#C0C0C0");
        dict.Add("Black", "#000000");
 
        List<KeyValuePair<string, string>> mappings = new List<KeyValuePair<string, string>>();
        foreach (var mapping in dict) {
            mappings.Add(mapping);
        }
 
        Console.WriteLine(String.Join(", ", mappings));
    }
}

 

posted on 2022-09-07 15:34  ZhYQ_note  阅读(33)  评论(0)    收藏  举报

导航