Dr. Blake
Dr. Blake

Reputation: 65

Update items in List<T> c#

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?

Upvotes: 2

Views: 16472

Answers (2)

Zohar Peled
Zohar Peled

Reputation: 82474

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

Upvotes: 8

Tim
Tim

Reputation: 2098

Nothing tricky, really (but does use System.Linq) **EDIT: Changed Single to First to avoid error if there are two users with the same name. **

void Update(string name, string newName)
{
    var user = userData.First(u => u.Name == name);
    user.Name = newName;
}

Notice this changes the object, and the List maintains reference to the changed object.

Upvotes: 1

Related Questions