‘!=’ 运算符不能应用于 ‘Student’ 和 ‘int’ 类型的操作数。

huangapple go评论74阅读模式
英文:

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;
    }
}

huangapple
  • 本文由 发表于 2023年3月31日 18:07:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75897275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定