开发者

Updating contents inside a list of structs

I have a List of structs

List<Student> studentList = new List<Student>()

and I want to find a specific student, then update it's information. To do that I have the following code inside a method

Student tmpStudent = new Student();
tmpStudent.fName = txtFName.Text;
studentList.Find(i => i.fName == tmpStudent.fName).fName.Replace(tmpStudent.fName, "newName");

but the problem us that it doesn't seem to be working. When I show the contents of the list of structs I still have the old version

string tmp = "";
foreach (Student s in studentList)
{
    tmp += s.fName + " " + s.lName + " " + s.Gpa.ToString() + "\n";
}
MessageBox.S开发者_如何学JAVAhow(tmp);

What is the correct way to achieve it?

Thanks


Replace does not do an "in place" replacement of a string - it returns a new string with the replaced text.

You need to assign the returned replaced string back to the fName property.

var foundStudent = studentList.Find(i => i.fName == tmpStudent.fName);
foundStudent.fName = foundStudent.fName.Replace(foundStudent.fName, "newName");

Though the second line appears to be overly verbose (you simply need to assign the new name):

var foundStudent = studentList.Find(i => i.fName == tmpStudent.fName);
foundStudent.fName = "newName";


Whay are you using Replace here? Why not just assign the new value directly?

Student s = studentList.Find(i => i.fName == txtFName.Text);
s.fName = "newName";

Also, structs should be immutable value-like types. Your Student type should be a class.


Since strings are immutable fName.Replace(tmpStudent.fName, "newName") returns a new string. This needs to be added to the struct,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜