Convert Dictionary, List.

论坛 期权论坛 脚本     
匿名技术用户   2020-12-29 15:08   22   0
Convert Dictionary, List. A Dictionary can be converted into a List. Specifically it is converted to a List of pairs. This requires the ToList extension method. ToList is part of the System.Linq extensions to the C# language.
Example. To start, we include the System.Collections.Generic and System.Linq namespaces. We create and populate a Dictionary collection. Next, we call ToList() on that Dictionary collection, yielding a List of KeyValuePair instances.

Then:We loop over the List instance, using a foreach-loop with the KeyValuePair iteration variable.

KeyValuePair

Finally:We print all the Key and Value properties with the Console.WriteLine method.

C# program that calls ToList on Dictionary

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

class Program
{
    static void Main()
    {
 Dictionary<string, int> dictionary = new Dictionary<string, int>();
 dictionary["cat"] = 1;
 dictionary["dog"] = 4;
 dictionary["mouse"] = 2;
 dictionary["rabbit"] = -1;

 // Call ToList.
 List<KeyValuePair<string, int>> list = dictionary.ToList();

 // Loop over list.
 foreach (KeyValuePair<string, int> pair in list)
 {
     Console.WriteLine(pair.Key);
     Console.WriteLine("   {0}", pair.Value);
 }
    }
}

Output

cat
   1
dog
   4
mouse
   2
rabbit
   -1
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP