List.ToDictionary可以简单的将List转换为Dictionary,非常方便。如果需要从数据库加载表,在程序中大量查表的应用场景,这个操作拥有较高的效率。
看示例:
1 2 3 4 5 6 7 |
public class Student { public int GradeId { get; set; } public int ClassId { get; set; } public int Sequence { get; set; } public string Name { get; set; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
List<Student> students = new List<Student>(); students.Add(new Student { GradeId = 1, ClassId = 1, Sequence = 1, Name = "张三", }); students.Add(new Student { GradeId = 1, ClassId = 1, Sequence = 2, Name = "李四", }); students.Add(new Student { GradeId = 2, ClassId = 1, Sequence = 1, Name = "王五", }); //ToDictionary(key构造,value构造) Dictionary<string,string> dictStudents = students.ToDictionary( x => x.GradeId.ToString()+"-"+x.ClassId.ToString()+"-"+x.Sequence.ToString(), x => x.Name); //得到“王五” var student2_1_name = dictStudents["2-1-1"]; |