-1

我有一堂课

class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
}

现在,我创建了一个学生对象列表:

List<Student> lst = new List<Student>();

该类的三个属性将来自三个不同的数据源。所以我不能一次添加对象的所有属性。我正在添加 ID 属性,如下所示:

lst.Add(new Student { ID = 1 }, new Student { ID = 2 })

现在我想在现有列表中设置“FirstName”或“LastName”属性的值。我怎么能做到这一点?

4

6 回答 6

1

您可以从与要更新的元素匹配的元素中获取索引:

int index= MyObjectList.FindIndex(x=>x.Id==object.Id);

并在更新后:

MyObjectList[index]=object;
于 2013-01-16T15:26:59.627 回答
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";
于 2012-06-17T08:35:07.077 回答
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
于 2012-06-17T08:39:49.247 回答
0

假设其他数据源包含studentId并且所有学生都有姓氏和名字。使用 linq加入lastNameListfirstNameList集合。您不需要的 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();
于 2012-06-17T08:56:34.933 回答
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";
于 2012-06-17T08:27:40.920 回答
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"));
于 2012-06-17T08:27:53.283 回答