c# - 更新结构列表中的内容

标签 c# list forms struct replace

我有一个结构列表

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

我想找到一个特定的学生,然后更新它的信息。为此,我在一个方法中包含以下代码

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

但问题是它似乎不起作用。当我显示结构列表的内容时,我仍然有旧版本

string tmp = "";
foreach (Student s in studentList)
{
    tmp += s.fName + " " + s.lName + " " + s.Gpa.ToString() + "\n";
}
MessageBox.Show(tmp);

正确的实现方式是什么?

谢谢

最佳答案

Replace 不会对字符串进行“就地”替换 - 它返回一个包含替换文本的新字符串。

您需要将返回的替换字符串分配回fName 属性。

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

虽然第二行看起来过于冗长(您只需要指定新名称):

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

关于c# - 更新结构列表中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4360809/

相关文章:

python - 获取列表列表中的唯一值

javascript - 动态更改 HTML 表单中 select 元素的名称

c# - 将每个方法包装在 try-catch 或代码的特定部分

c# - CIL 和 JVM C#​​ 和 Java 中的小端到大端

c# - 使用 .Net 生成 SHA256 哈希的不同结果和 react native 库(相同输入)

c# - 如何更快地打开winform?

使用队列列表的 Python 多处理

regex - 将目录内容打印到文件的 ant 任务

javascript - javascript 是否强制使用特定的字符集?

javascript - 使用表单时数据乱码