I have a list which I want to update using LINQ.
class Student
{
private string name;
private int marks;
public string Name { get; set;}
pub
As others have pointed out, LINQ is for querying data, it is not for doing updates.
You should iterate your list, and modify your values like:
foreach (var student in myList)
{
if (student.Name == "Tom")
{
student.Marks = 35;
}
}
Or
foreach (var student in myList.Where(r => r.Name == "Tom"))
{
student.Marks = 35;
}
Whatever you think better conveys the intent use that.
but here is an interesting thing:
If you have a statement like:
myList.Where(w => w.Name == "Tom").Select(w => w.Marks = 35).ToList();
Without assigning the result back to myList
the above query will modify the value in the original list. Remember, it is a side effect and it is not the proper way to update. This is modification can be explained by reference parameter being passed to a method and getting modified there. But Importantly, this should always be avoided. It is a bad practice and could lead to really confusing code. Use LINQ for querying only.