C#数组中List, Dictionary的相互转换问题

2019-12-30 15:30:41于丽

运行程序

#a666b152753b4fb6c003e1eb5ba6cefc#

将数组转换为Dictionary

将数组转换成Dictionary,使用ToDictionary()扩展方法。这里就可以用StudentArray.ToDictonary(

看这个方法需要的参数,第一个参数需要键和第二个参数需要值。我们知道Dictionary是一个泛型,它是键/值对类型的集合。因此,这里我们用一个lambda表达式传递Dictionary对象名称。


StudentArray.ToDictionary(key => key.Id,Studentobj => Studentobj);

这个ToDictionary方法返回的类型是Dictionary 对象。 其键/值对<int,Student>类型,同样说明我们可以创建一个该类型的对象来存储ToDictionary方法得到的数据。


Dictionary<int, Student> StudentDictionary = StudentArray.ToDictionary(key => key.Id,Studentobj => Studentobj);

使用foreach从这个StudentDictionary对象遍历学生资料,如下:


foreach (KeyValuePair<int, Student> student in StudentDictionary)
{
 Console.WriteLine("Id = "+student.Key+" "+" Name = "+student.Value.Name+" "+" Gender = "+student.Value.Gender);
}

运行程序

c#,数组,list,dictionary,转换

将Dictionary转换为数组

将Dictionary转换成数组,使用ToArray扩展方法。在之前,需要获取Dictionary对象的集合中的值,所以我们使用Values属性的ToArray方法。


Student[] DictionaryToArray = StudentDictionary.Values.ToArray();

使用foreach遍历学生资料


foreach (Student student in DictionaryToArray)
{
 Console.WriteLine("Id = "+student.Id+" "+" Name = " +student.Name+" "+" Gender = "+student.Gender);
}

运行程序

c#,数组,list,dictionary,转换

将List转换为Dictionary

之前已经创建了一个StudentList学生对象,将StudentList转换为Dictionary我们调用ToDictionary方法。


Dictionary<int, Student> ListToDictionary = StudentList.ToDictionary(key => key.Id, value => value);

对于ToDictionary方法的两个参数,我们分别通过键和值传递其对象。这里ToDictionary被赋值,并返回了一个< int,Student >Dictionary 对象。所以我们创建该类型的对象然后存储返回的数据,最后用foreach获取学生资料。


foreach (KeyValuePair<int,Student> student in ListToDictionary)
{
 Console.WriteLine("Id = "+student.Key+" "+" Name = " +student.Value.Name+" "+" Gender = "+student.Value.Gender);
}