ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

Replace

This extension method replaces an item in a collection that implements the ilist<t> interface

Source

/// <summary>
/// This extension method replaces an item in a collection that implements the IList interface.
/// </summary>
/// <typeparam name="T">The type of the field that we are manipulating</typeparam>
/// <param name="thisList">The input list</param>
/// <param name="position">The position of the old item</param>
/// <param name="item">The item we are goint to put in it's place</param>
/// <returns>True in case of a replace, false if failed</returns>
public static bool Replace<T>(this IList<T> thisList, int position, T item)
{
   if (position > thisList.Count - 1)
      return false;
   // only process if inside the range of this list

   thisList.RemoveAt(position);
   // remove the old item
   thisList.Insert(position, item);
   // insert the new item at its position
   return true;
   // return success
}

Example

List<string> strg = new List<string> { "test", "tesssssst2" };
strg.Replace(1,"test2");

foreach (string str in strg)
   Console.WriteLine(str);

Console.ReadKey();

Output : 
test
test2

Author: Otto Beragg

Submitted on: 5 mrt 2008

Language: C#

Type: System.Collections.Generic.IList<T>

Views: 7608