保存对象列表中的项
本文关键字:列表 对象 保存 | 更新日期: 2023-09-27 18:16:10
我有以下类:
public class Student : ModelObject
{
private string name;
private string id;
public string Name
{
get { return name; }
set { name = value; }
}
public string Id
{
get { return id; }
set { id = value; }
}
我有以下列表
protected List<Student> studentlist = new List<Student>();
这个列表已经充满了学生对象,我想要实现的是创建一个字符串列表,例如:
List<string> ownlist = new List<string>();
保存每个Object的id。
这个想法是获取列表studentlist的内容,它已经满了,并且对于该列表的每个元素(即对象),将id的值保存为ownlist的一个元素。
有很多方法。第一个-简单迭代:
foreach(var item in studentlist)
{
ownList.Add(item.Id);
}
Linq:
List<string> ownlist = studentlist.Select(x => x.Id).ToList();
你可以使用c# Dictionary:
Dictionary<int, Student> record = new Dictionary<int, Student>
foreach(Student std in studentlist)
{
records.Add(std.Id, std);
}