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<string, int> d = new Dictionary<string, int>();
var l = d.ToList();
List<KeyValuePair<string, int>> l2 = new List<KeyValuePair<string, int>>{
new KeyValuePair<string,int>("a", 1),
new KeyValuePair<string,int>("b", 2)
};
// list -> dict 两种转换方式
// 1. 可指定 keySelector 和 valueSelector;完全自定义字典 key, value 的类型
Dictionary<string, int> d2 = l2.ToDictionary(entry => entry.Key, entry => entry.Value);
// 2. 也可只指定 keySelector, value 为 entry 的值。
Dictionary<float, KeyValuePair<string, int>> d3 = l2.ToDictionary(
entry => (float)entry.Value);
}
}
}
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<string, int> d = new Dictionary<string, int>();
var l = d.ToList();
List<KeyValuePair<string, int>> l2 = new List<KeyValuePair<string, int>>{
new KeyValuePair<string,int>("a", 1),
new KeyValuePair<string,int>("b", 2)
};
// list -> dict 两种转换方式
// 1. 可指定 keySelector 和 valueSelector;完全自定义字典 key, value 的类型
Dictionary<string, int> d2 = l2.ToDictionary(entry => entry.Key, entry => entry.Value);
// 2. 也可只指定 keySelector, value 为 entry 的值。
Dictionary<float, KeyValuePair<string, int>> d3 = l2.ToDictionary(
entry => (float)entry.Value);
}
}
}