Anshuman
Anshuman

Reputation: 110

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

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?

Upvotes: 1

Views: 634

Answers (3)

Anshuman
Anshuman

Reputation: 110

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.

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117144

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

Upvotes: 1

Felix An
Felix An

Reputation: 543

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...

Upvotes: 2

Related Questions