How to update value in a List using LINQ

后端 未结 9 976
天命终不由人
天命终不由人 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条回答
  •  猫巷女王i
    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 testList = new List()
                {
                    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!!

提交回复
热议问题