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

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

本篇文章会向大家实例讲述以下内容:

将数组转换为List 将List转换为数组 将数组转换为Dictionary 将Dictionary 转换为数组 将List转换为Dictionary 将Dictionary转换为List

首先这里定义了一个“Student”的类,它有三个自动实现属性。


class Student 
 {
 public int Id { get; set; }
 public string Name { get; set; }
 public string Gender { get; set; }
 }

将数组转换为List

将数组转换成一个List,我先创建了一个student类型的数组。


static void Main (string[] args) 
 {
  //创建数组
  Student[] StudentArray = new Student[3];
  //创建创建3个student对象,并赋值给数组的每一个元素  StudentArray[0] = new Student()
  {
  Id = 203,
  Name ="Tony Stark",
  Gender ="Male"
  };
  StudentArray[1] = new Student()
  {
  Id = 205,
  Name="Hulk",
  Gender = "Male"
  };
  StudentArray[2] = new Student() 
  {
  Id = 210,
  Name ="Black Widow",
  Gender="Female"
  };

接下来,使用foreach遍历这个数组。


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

运行程序

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

接下来将这个数组转换为List,我们添加System.Linq命名空间,然后调用ToList()扩展方法。这里我们就调用StudentArray.ToList()

注意这个ToList方法的返回类型,它返回的是List< Student >对象,这说明我们可以创建一个该类型的对象来保存ToList方法返回的数据。


List<Student> StudentList = StudentArray.ToList<Student>();

使用foreach从StudentList中获取所有的学生资料。


List<Student> StudentList = StudentArray.ToList<Student>();
foreach (Student student in StudentList)
 {
 Console.WriteLine("Id = "+student.Id+" "+" Name = "+student.Name+" "+" Gender = "+student.Gender);
 }

运行程序

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

将List转换为数组

将List转换为数组,使用System.Linq命名空间下的ToArray()扩展方法。


Student[] ListToArray = StudentList.ToArray<Student>();

使用foreach遍历学生资料


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