Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update items in List<T> c#

Tags:

c#

list

I have a class to handle some data :

public class User
{
  public string Name;
  public string Date;
}

In another class,i create a List of User class and add data as follows :

public class Display
{
  List<User> userData = new List<User>;

  private void add()
  {
    User udata = new User;
    udate.Name = "Abc";
    udata.Date = "1/1/18";
    userData.Add(udata);
  }
}

My question is, after adding some data,how do i update it ? Say i have added a data(udata is what i mean) with a Name of ABC,how do i update it?

like image 904
Dr. Blake Avatar asked Feb 13 '26 18:02

Dr. Blake


1 Answers

Since your list contains a mutable type, all you need to do is get a reference to the specific item you want to update.
That can be done in a number of ways - using it's index, using the Find method, or using linq are the first three that comes to mind.

Using index:

userData[0]?.Name = "CBA";

Using Find:

userData.Find(u => u.Name = "Abc")?.Name = "CBA";

Using linq (FirstOrDefault is not the only option):

userData.FirstOrDefault(u => u.Name = "Abc")?.Name = "CBA";

Note the use of null conditional operator (]? and .?) it prevents a null reference exception in case the item is not found.

Update

As Ak77th7 commented (thanks for that!), the code in this answer wasn't tested and will cause a compilation error -

error CS0131: The left-hand side of an assignment must be a variable, property or indexer

The reason for this is the null-conditional operator (?.). You can use it to get values from properties, but not for setting them.

The fix is either to accept the fact that your code might throw a NullReferenceException (which I personally believe has no room in production-grade code) or to make your code a bit more cumbersome:


// Note: Possible null here!
userData.Find(u => u.Name.EndsWith("1")).Name = "Updated by Find";

// Safe, but cumbersome
var x = userData.FirstOrDefault(u => u.Name.EndsWith("2"));
if(x is not null)
{
    x.Name = "Updated by FirstOrDefault";
}

See a live demo on SharpLab.IO

like image 151
Zohar Peled Avatar answered Feb 15 '26 08:02

Zohar Peled



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!