我有一个班级
class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
}
现在,我创建了一个Student对象列表:
List<Student> lst = new List<Student>();
该类的三个属性将来自三个不同的数据源。所以我不能一次添加对象的所有属性。我正在添加ID属性如下:
lst.Add(new Student { ID = 1 }, new Student { ID = 2 })
现在我想在现有列表中设置“FirstName”或“LastName”属性的值。我怎么能这样做?
答案 0 :(得分:1)
List<Student> lst = new List<Student>();
lst.Add(new Student { ID = 1 });
lst.Add(new Student { ID = 2 });
//Get the student you want by id then use that to populate the remaining properties
var temp = lst.Single(l => l.ID == 1);
temp.FirstName = "fname";
temp.LastName = "lastname";
答案 1 :(得分:1)
不要混用方法Add()
来电:
list.Add(new Student());
和集合初始化语法:
List<Student> list = new List<Student>
{
new Student(),
new Student()
};
然后
int index = 1;
Student student = list[index]; // may cause IndexOutOfRangeException
student.Name = "Me"; // may cause NullReferenceException
或更短:
list[i].Name = "Me"; // may cause them both too
答案 2 :(得分:1)
您可以从与要更新的元素匹配的元素中获取索引:
int index= MyObjectList.FindIndex(x=>x.Id==object.Id);
并在更新后:
MyObjectList[index]=object;
答案 3 :(得分:0)
您可以使用list.count-1获取列表中的最后一项。然后,您可以更新所需的属性。
List<Student> lst=new List<Student>();
lst.Add(new Student { ID = 1, FirstName = "FirstName", LastName = "LastName" });
//Then get props from other datasource
lst[lst.Count-1].FirstName="FirstName";
lst[lst.Count-1].LastName="LastName";
答案 4 :(得分:0)
我只在这里猜测...如果,不起作用尝试;
lst.Add(new Student{ID=2, FirstName="The", LastName="Stig"});
或者您可以为Student对象定义构造函数...
public Student(int mID, string mFirstName, string mLastName)
{
ID = mID;
FirstName = mFirstName;
LastName = mLastName;
}
然后使用
lst.Add(new Student(2, "The", "Stig"));
答案 5 :(得分:0)
假设其他数据源包含studentId
,并且所有学生都有姓氏和名字。
使用linq加入lastNameList
和firstNameList
个集合。您不需要的studentId列表,因为其他两个也具有该值。
var list =
(from lastName in lastNameList
join firstName in firstNameList on lastName.studentId equals firstName.studentId
select new Student()
{
.ID = lastName.studentId,
.FirstName = firstName.Name,
.LastName = lastName.Name
}).ToList();