How to update value in a List using LINQ

后端 未结 9 973
天命终不由人
天命终不由人 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.

    0 讨论(0)
  • 2020-12-31 15:44

    Objects are stored by reference in the list so you can recover object via linq and then edit, it will be reflect the changes on the list.

    Example

        static void Main(string[] args)
            {
                List<Entity> testList = new List<Entity>()
                {
                    new Entity() {Id = 1, Text = "Text"},
                    new Entity() {Id = 2, Text = "Text2"}
                };
    
                Console.WriteLine($"First text value:{testList[1].Text}");
    
                Entity entityToEdit = testList.FirstOrDefault(e => e.Id == 2);
                if (entityToEdit != null)
                    entityToEdit.Text = "Hello You!!";
    
                Console.WriteLine($"Edited text value:{testList[1].Text}");
                
                Console.ReadLine();
            }
    
     internal class Entity
        {
            public int Id { get; set; }
            public String Text { get; set; }
        }
    

    Testing the app you will get the follow result:

    First text value:Text2

    Edited text value:Hello You!!

    0 讨论(0)
  • 2020-12-31 15:45

    Above can be achieved by just assign the value back to the collection

    myList = myList
            .Where(w => w.Name == "Tom")
            .Select(w=> { w.Marks = 35; return w})
            .ToList();
    
    0 讨论(0)
提交回复
热议问题