Home > Enterprise >  How can I change a object's (present in a list) field?
How can I change a object's (present in a list) field?

Time:07-28

For example: There's a list : list<student> Students . It consists of { Id, Name, Marks} where id is unique. Suppose I want to change marks of a particular object. How do I do it?

CodePudding user response:

You may simply access the objects by index and change their fields:

Students[0].Marks = 100; // changing the mark of the 0th student to 100, assuming Marks is an int
Students[1].Marks = 90;
// etc...

CodePudding user response:

I would suggest that this is a more modern way of doing what you need:

var student = Students.Where(s => s.Id == targetId).FirstOrDefault();
if (student != null)
{
    student.Marks = newValue;
}

CodePudding user response:

So based on answers and comments, I have come to following conclusion and it works as desired.

int targetId;  //can be taken input
int newValue;  //can be taken input
...
for (int i = 0; i < Students.Count(); i  )
  if(Students[i].Id == targetId)
    Students[i].Marks = newValue; 

I will also try to explore dictionary approach to handle data.

  • Related