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;
}
Written by Blaise Liu
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#List
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#