- 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 StudentList = StudentArray.ToList();
foreach (Student student in StudentList)
{
Console.WriteLine("Id = " + student.Id + " " + " Name = " + student.Name + " " + " Gender = " + student.Gender);
}
2. List转换为Array
Student[] ListToArray = StudentList.ToArray();
foreach (Student student in ListToArray)
{
Console.WriteLine("Id = " + student.Id + " " + " Name = " + student.Name + " " + " Gender = " + student.Gender);
}
3. Array转Dictionary
Dictionary StudentDictionary = studentArray.ToDictionary(key=>key.Id, Studentobj => Studentobj);
foreach (KeyValuePair 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 ListToDictionary = ListToArray.ToDictionary(key => key.Id, value => value);
foreach (KeyValuePair student in ListToDictionary)
{
Console.WriteLine("Id = " + student.Key + " " + " Name = " + student.Value.Name + " " + " Gender = " + student.Value.Gender);
}
6. Dictionary转List
List 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 ListUser = new List();
PassUser = ListUser.AsQueryable();