Here are Tim S's examples as extension methods on top of the Collection Class:
CS with FirstOrDefault
<!-- language: lang-cs -->
public static void ReplaceItem<T>(this Collection<T> col, Func<T, bool> match, T newItem)
{
var oldItem = col.FirstOrDefault(i => match(i));
var oldIndex = col.IndexOf(oldItem);
col[oldIndex] = newItem;
}
CS with Indexed Loop
<!-- language: lang-cs -->
public static void ReplaceItem<T>(this Collection<T> col, Func<T, bool> match, T newItem)
{
for (int i = 0; i <= col.Count - 1; i++)
{
if (match(col[i]))
{
col[i] = newItem;
break;
}
}
}
Usage
Imagine you have this class setup
<!-- language: lang-cs -->
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
You can call either of the following functions/implementations like this where the match
parameter is used to identify the item you'd like to replace:
<!-- language: lang-cs -->
var people = new Collection<Person>
{
new Person() { Id = 1, Name = "Kyle"},
new Person() { Id = 2, Name = "Mit"}
};
people.ReplaceItem(x => x.Id == 2, new Person() { Id = 3, Name = "New Person" });
VB with Indexed Loop
<!-- language: lang-vb -->
<Extension()>
Public Sub ReplaceItem(Of T)(col As Collection(Of T), match As Func(Of T, Boolean), newItem As T)
For i = 0 To col.Count - 1
If match(col(i)) Then
col(i) = newItem
Exit For
End If
Next
End Sub
VB with FirstOrDefault
<!-- language: lang-vb -->
<Extension()>
Public Sub ReplaceItem(Of T)(col As Collection(Of T), match As Func(Of T, Boolean), newItem As T)
Dim oldItem = col.FirstOrDefault(Function(i) match(i))
Dim oldIndex = col.IndexOf(oldItem)
col(oldIndex) = newItem
End Sub