- Array转换为List
- List转换为Array
- Array转Dictionary
- Dictionary转Array
- List转Dictionary
- Dictionary转List
- IQueryable,IEnumerable,List相互转换
基本资料, 定义Student类,并添加属性
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
}
//创建数组
Student[] StudentArray = new Student[3];
StudentArray[0] = new Student()
{
Id = 12,
Name = "Lucky",
Gender = "Male"
};
StudentArray[1] = new Student()
{
Id = 23,
Name = "Poppy",
Gender = "Male"
};
StudentArray[2] = new Student()
{
Id = 55,
Name = "Jack",
Gender = "Female"
};
1. Array转换为List
List<Student> StudentList = StudentArray.ToList<Student>();
foreach (Student student in StudentList)
{
Console.WriteLine("Id = " + student.Id + " " + " Name = " + student.Name + " " + " Gender = " + student.Gender);
}
2. List转换为Array
Student[] ListToArray = StudentList.ToArray<Student>();
foreach (Student student in ListToArray)
{
Console.WriteLine("Id = " + student.Id + " " + " Name = " + student.Name + " " + " Gender = " + student.Gender);
}
3. Array转Dictionary
Dictionary<int, Student> StudentDictionary = studentArray.ToDictionary(key=>key.Id, Studentobj => Studentobj);
foreach (KeyValuePair<int, Student> student in StudentDictionary)
{
Console.WriteLine("Id = " + student.Key + " " + " Name = " + student.Value.Name + " " + " Gender = " + student.Value.Gender);
}
4. Dictionary转Array
Student[] DictionaryToArray = StudentDictionary.Values.ToArray();
foreach (Student student in DictionaryToArray)
{
Console.WriteLine("Id = " + student.Id + " " + " Name = " + student.Name + " " + " Gender = " + student.Gender);
}
5. List转Dictionary
Dictionary<int, Student> ListToDictionary = ListToArray.ToDictionary(key => key.Id, value => value);
foreach (KeyValuePair<int, Student> student in ListToDictionary)
{
Console.WriteLine("Id = " + student.Key + " " + " Name = " + student.Value.Name + " " + " Gender = " + student.Value.Gender);
}
6. Dictionary转List
List<Student> DictionaryToList = StudentDictionary.Values.ToList();
foreach (Student student in DictionaryToList)
{
Console.WriteLine("Id = " + student.Id + " " + " Name = " + student.Name + " " + " Gender = " + student.Gender);
}
IQueryable,IEnumerable都可以通过ToList()转换为类型。
PassUser.ToList();
如果需要反向转换,有两个很好用的方法AsQueryable(),AsEnumerable(),可以顺利将List转换为IQueryable,IEnumerable。
List<MO> ListUser = new List<MO>();
PassUser = ListUser.AsQueryable();