How to update value in a List using LINQ

后端 未结 9 903
天命终不由人
天命终不由人 2020-12-31 14:45

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         


        
9条回答
  •  迷失自我
    2020-12-31 15:41

    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.

提交回复
热议问题