Dictionary转换为list

本文导读:ASP.NET中dictionary和list都用于集合类,在开发中,经常对List、Dictionary列表进行复制、转换等操作,有时需要将Dictionary转换为list 或者 list转换为Dictionary。下面介绍Dictionary转换为list的几种方式

 一、创建List的时候,将Dictionary的Value值作为参数

 

 
Dictionary<int, Person> dic = new Dictionary<int, Person>();
List<Person> pList = new List<Person>(dic.Values);

 

二、用Dictionary对象自带的ToList方法

 

 
Dictionary<int, Person> dic = new Dictionary<int, Person>();
List<Person> pList=new List<Person>();
pList = dic.Values.ToList<Person>();

 

三、建立List,循环Dictionary逐个赋值

 

Dictionary<int, Person> dic = new Dictionary<int, Person>();
List<Person> pList=new List<Person>();
foreach (var item in dic)
{
   pList.Add(item.Value);
}

 

四、创建List后,调用List.AddRange方法

 

 
Dictionary<int, Person> dic = new Dictionary<int, Person>();
List<Person> pList=new List<Person>();
pList.AddRange(dic.Values);

 

五、通过Linq查询,得到结果后调用ToList方法

 

 
Dictionary<int, Person> dic = new Dictionary<int, Person>();
List<Person> pList=new List<Person>();
pList = (from temp in dic select temp.Value).ToList();

posted on 2017-10-21 01:09  卡农2014  阅读(414)  评论(0)    收藏  举报

导航