如何将通用列表转换为数组? [英] How to convert a Generic List to an Array?
本文介绍了如何将通用列表转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
List<student> studIDList = handler.GetStudentIDList();
int[] studID = studIDList.ToArray();
这是我的代码,但它不起作用。
假设已填充studIDList。
提前谢谢。
http://www.codeproject.com/script/Membership/View .aspx?mid = 8136054 [ ^ ]
推荐答案
您无法转换的
类实例到整数 - 系统不知道怎么做。列表
学生
但是,如果学生
class有一个整数属性,例如你可以得到一组数字的ID号:
You can't convert aList
ofstudent
class instances to integers - the system doesn't know how to do that.
But, if thestudent
class has an integer property such as an ID number you can get an array of those:
List<student> studIDList = handler.GetStudentIDList();
int[] studID = studIDList.Select(s => s.Id).ToArray();
错别字 - OriginalGriff [/ edit]
[edit]Typos - OriginalGriff[/edit]
1。方法ToArray()返回一个Student
对象的数组;
2.如果需要整数数组使用学生的ID,你必须迭代你的第一个列表并创建一个ID列表,然后在第二个列表中使用ToArray(),如下例所示:
1.The method ToArray() returns an array ofStudent
objects;
2.If you need an array of integer with the ID of the students, you have to iterate your first list and create a list of IDs, then to use ToArray() on this 2nd list, like in example bellow:
List<student> studIDList = handler.GetStudentIDList();
List<int> idList= new List<int>;
foreach(student item in studIDList)
{
idList.Add(item.ID); //Here you should use the property used for student ID!
}
//
int[] studID = idList.ToArray();
除了解决方案2:
迭代是在一行中使用已经在类中实现的方法System.Collections.Generic.List<>
:
http://msdn.microsoft.com/en-us/library/73fe8cwf%28v=vs.110%29.aspx [ ^ ]。
-SA
In addition to Solution 2:
The iteration is made in one line using the method already implemented in the classSystem.Collections.Generic.List<>
:
http://msdn.microsoft.com/en-us/library/73fe8cwf%28v=vs.110%29.aspx[^].
—SA
这篇关于如何将通用列表转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文