Last Updated: February 25, 2016
·
488
· blaiseliu

Replace an item in a List

Looks like there is no convenient way to do it. Unlike a Dictionary, List has no key to reference with. The only way to replace an item in a list is by using its index:

int index = listofelements.IndexOf(oldValue);
if(index != -1) listofelements[index] = newValue;

This requires us to locate the oldValue with our key. Here is an example. A method to add a contact by its position:

private static void ReplaceContact(IList<LhdContact> contacts, LhdContact newContact)
{
    var oldContact =
        contacts.FirstOrDefault(c => c.Type.Equals(newContact.Type, StringComparison.OrdinalIgnoreCase));
    var index = contacts.IndexOf(oldContact);
    if (index != -1) contacts[index] = newContact;
}