首页 > 代码库 > Dictionary CovertTo List

Dictionary CovertTo List

假设有如下一个Dictionary 要转换成List 
 
Dictionary<string, string> dicNumber = new Dictionary<string, string>();    List<string> listNumber = new List<string>();    dicNumber.Add("a", "First");    dicNumber.Add("b", "Second");    dicNumber.Add("c", "Third");
 
有如下几种方法:
 

Enumerable.Select<TSource, TResult> 方法 (IEnumerable<TSource>, Func<TSource,TResult>)

将序列中的每个元素投影到新表中。 (由 Enumerable 定义。)

1.listNumber=dicNumber.Select(kvp=>kvp.Key).ToList()    上面代码中:kvp=>kvp.Key 将Dictionary中的每个元素投影到新表中,Func并返回TResult,然后把结果转成List
 
Dictionary.Keys 获取包含 Dictionary<TKey, TValue> 中的键的集合
2.listNumber=dicNumber.Keys.ToList();    3.foreach(var item in dicNumber)
{       listNumber.Add(item.key);   }      4.var keys=new List<string>(dicNumber.Keys);
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>