4fvvxg
Last Updated: February 25, 2016
·
228
· blaiseliu
0 zdfer mextupleu3bexrr3szkfrkbdj3chrcr3youxf8zsotmf0kvtoxe7u7xapdqodnqquhhlpg

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;
}
Say Thanks
Respond