1

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.Show(tmp);

What is the correct way to achieve it?

Thanks

esausilva
  • 1,964
  • 4
  • 26
  • 54

3 Answers3

4

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";
Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

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

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216