博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

泛型 List 和 Dictionary 类的互相转换

Posted on 2008-01-11 10:11  Snapping  阅读(2318)  评论(1编辑  收藏  举报
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testcs
{
    
class Program
    {
        
static void Main(string[] args)
        {
            ListAndDictionary();

        }

        
/// <summary>
        
/// 泛型 List 和 Dictionary 类的互相转换
        
/// </summary>
        private static void ListAndDictionary()
        {
            
// dict -> list 
            
// 转换为 List<T>,T 的类型是 KeyValuePair<TKey, TValue>
            Dictionary<stringint> d = new Dictionary<stringint>();
            var l 
= d.ToList();

            List
<KeyValuePair<stringint>> l2 = new List<KeyValuePair<stringint>>{
                
new KeyValuePair<string,int>("a"1),
                
new KeyValuePair<string,int>("b"2)
            };


            
// list -> dict 两种转换方式

            
// 1. 可指定 keySelector 和 valueSelector;完全自定义字典 key, value 的类型            
            Dictionary<stringint> d2 = l2.ToDictionary(entry => entry.Key, entry => entry.Value);
            
// 2. 也可只指定 keySelector, value 为 entry 的值。
            Dictionary<float, KeyValuePair<stringint>> d3 = l2.ToDictionary(
                entry 
=> (float)entry.Value);
        }
    }
}