How to update value in a List using LINQ

后端 未结 9 939
天命终不由人
天命终不由人 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: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();
    

提交回复
热议问题