How to update value in a List using LINQ

后端 未结 9 972
天命终不由人
天命终不由人 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:19

    LINQ is for querying, not for updating the data. Use LINQ to get the items that you want to modify, and then modify them in a foreach loop:

    foreach ( var tom in myList.Where(w => w.Name == "Tom")) {
        tom.Marks = 35;
    }
    

    Demo.

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

    Select(), like any other LINQ method, doesn't change a source collection, instead, it return a new collection.

    So you should either assign that new collection to myList:

    myList = myList.Where(w => w.Name == "Tom").Select(w => { w.Marks = 35; return w}).ToList();
    

    or assign Marks property in a separate foreach loop

    myList.Where(w => w.Name == "Tom").ToList().ForEach(w => w.Marks = 35);
    
    0 讨论(0)
  • 2020-12-31 15:24

    This is kind of clunky, but works, and doesn't depend on being passed a reference. It creates a new list based on the old.

    var myList=myList.Select(l=>new Student { 
       l.Name,
       Marks=l.Name=="Tom"?35:l.Marks}).ToList();
    

    Or more silly:

    var myList=myList.Where(l=>l.Name!="Tom").Union(
      myList.Where(l=>l.Name=="Tom").Select(l=>new Student { 
       l.Name,
       Marks=35})).ToList();
    
    0 讨论(0)
  • 2020-12-31 15:25

    how about old good for loop

    for(int i = 0; i < myList.Count; i++)
    if (myList[i].Name  == "Tom")
    {
        myList[i].Marks = 35;
        break;
    }
    
    0 讨论(0)
  • 2020-12-31 15:26

    well @dasblinkenlight code should work but you can also try something like this

     var query = from x in list
                 where x.Name = yourcondition
                 select new { x };
    foreach(var item in query)
       item.x.FieldToUpdate = SetValue;
    
    0 讨论(0)
  • 2020-12-31 15:27

    Try:

    myList .Where(w=> w.Name  == "dTomi").ToList().ForEach(i => i.Marks  = 35);
    
    0 讨论(0)
提交回复
热议问题