英文:
Operator '!=' cannot be applied to operands of type 'Student' and 'int'
问题
我尝试将索引变量也更改为仍然给出相同的错误
public void UpdateStudent(int rollNo, Student updatedStudent)
{
var index = _list.FirstOrDefault(s => s.RollNo == rollNo);
if (index != null)
{
index.Name = updatedStudent.Name;
index.RollNo = updatedStudent.RollNo;
index.Marks = updatedStudent.Marks;
index.Branch = updatedStudent.Branch;
index.Location = updatedStudent.Location;
}
}
我已尝试更改其类型
英文:
I tried making index var also still it gives the same error
public void UpdateStudent(int rollNo, Student updatedStudent)
{
var index = _list.FirstOrDefault(s => s.RollNo == rollNo);
if (index != -1)
{
index.Name = updatedStudent.Name;
index.RollNo = updatedStudent.RollNo;
index.Marks = updatedStudent.Marks;
index.Branch = updatedStudent.Branch;
index.Location = updatedStudent.Location;
}
}
I have tried changing it type
答案1
得分: 3
FirstOrDefault
返回列表中的项,而不是项的索引!
你应该使用item!=null
进行检查,如下所示:
public void UpdateStudent(int rollNo, Student updatedStudent)
{
var item = _list.FirstOrDefault(s => s.RollNo == rollNo);
if (item != null)
{
item.Name = updatedStudent.Name;
item.RollNo = updatedStudent.RollNo;
item.Marks = updatedStudent.Marks;
item.Branch = updatedStudent.Branch;
item.Location = updatedStudent.Location;
}
}
英文:
FirstOrDefault
returns the item from the list, not the index of the item!
you should check with item!=null
like so :
public void UpdateStudent(int rollNo, Student updatedStudent)
{
var item = _list.FirstOrDefault(s => s.RollNo == rollNo);
if (item != null)
{
item.Name = updatedStudent.Name;
item.RollNo = updatedStudent.RollNo;
item.Marks = updatedStudent.Marks;
item.Branch = updatedStudent.Branch;
item.Location = updatedStudent.Location;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论