locked
How can i update a list with new values using Linq ? RRS feed

  • Question

  • User1253338400 posted

    Hi ,

    I have a list which i have populated and returned to my controller. (the primary list)

    I also have a second list which are new entries to decide if they are to be added to the primary list or update existing value in the primary list.


                             foreach (var obj in mydataTest)
                             {                              
                                   if (primaryList.Any(x => x.Id  == "1" && x.objectType == obj.ObjectTye && x.Name == obj.Name && x.Address == item.Address ))
                                  {      
                                          //it exists in the primary list so just do an update   ??                                                                                            }                          
                                  }    
                              }
     

     How can i update the values in the primarylist with values from the mydataTest list ?   

    thanks

    Thursday, October 24, 2019 3:44 AM

Answers

  • User1120430333 posted

    You can try it in the foreach loop.

    var hit = (from a in primaryList.where((x => x.Id == "1" && x.objectType == obj.ObjectTye && x.Name == obj.Name && x.Address == item.Address )).SingleOrDefault();
    
    if (hit != null)
    {
         hit.Name = "Soemthing";
    }

    If I am not mistaken,  "hit" object  still points back to the object in the list.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 24, 2019 2:19 PM

All replies

  • User1120430333 posted

    You can try it in the foreach loop.

    var hit = (from a in primaryList.where((x => x.Id == "1" && x.objectType == obj.ObjectTye && x.Name == obj.Name && x.Address == item.Address )).SingleOrDefault();
    
    if (hit != null)
    {
         hit.Name = "Soemthing";
    }

    If I am not mistaken,  "hit" object  still points back to the object in the list.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 24, 2019 2:19 PM
  • User-17257777 posted

    Hi robby32,

    Use Linq to find the object, if it existes, then update it with new value.

    foreach(var obj in mydataTest)
                {
                    var oldobj = primaryList.FirstOrDefault(x => x.Id  == "1" && x.objectType == obj.ObjectTye && x.Name == obj.Name && x.Address == item.Address);
    
                    if(oldobj != null)
                    {
                        //...
    
                        //oldobj.Address = "xxx";
                        //oldobj.objectType = "xxx";
    
                        //...
                    }
                }

    Best Regards,

    Jiadong Meng

    Friday, October 25, 2019 5:56 AM