Full repo available at https://bitbucket.org/createdbyx/codefarts.utilities-extension-methods-only
namespace System.Collections
{
/// <summary>
/// Provides extension methods for the IList interface.
/// </summary>
public static class IListExtensionMethods
{
/// <summary>Swaps the specified items in a list.</summary>
/// <param name="list">The list.</param>
/// <param name="indexA">The index of item A.</param>
/// <param name="indexB">The index of item B.</param>
/// <param name="remove">If set to <c>true</c> items will be removed and re-inserted.</param>
public static void Swap(this IList list, int indexA, int indexB, bool remove)
{
if (indexA == indexB)
{
return;
}
indexA.IsInRange(0, list.Count - 1, true, "indexA is out of range.");
indexB.IsInRange(0, list.Count - 1, true, "indexB is out of range.");
if (remove)
{
var first = Math.Min(indexA, indexB);
var second = Math.Max(indexA, indexB);
var tempA = list[first];
var tempB = list[second];
list.RemoveAt(second);
list.RemoveAt(first);
list.Insert(first, tempB);
list.Insert(second, tempA);
}
else
{
var temp = list[indexA];
list[indexA] = list[indexB];
list[indexB] = temp;
}
}
/// <summary>Swaps the specified items in a list.</summary>
/// <param name="list">The list.</param>
/// <param name="indexA">The index of item A.</param>
/// <param name="indexB">The index of item B.</param>
/// <remarks>Items are swapped and not removed or inserted.</remarks>
public static void Swap(this IList list, int indexA, int indexB)
{
Swap(list, indexA, indexB, false);
}
/// <summary>Swaps the specified items in a list and return true if successful.</summary>
/// <param name="list">The list.</param>
/// <param name="indexA">The index of item A.</param>
/// <param name="indexB">The index of item B.</param>
/// <remarks>Items are swapped and not removed or inserted.</remarks>
/// <returns>true if successful.</returns>
public static bool TrySwap(this IList list, int indexA, int indexB)
{
try
{
Swap(list, indexA, indexB);
}
catch
{
return false;
}
return true;
}
/// <summary>Swaps the specified items in a list and return true if successful.</summary>
/// <param name="list">The list.</param>
/// <param name="indexA">The index of item A.</param>
/// <param name="indexB">The index of item B.</param>
/// <param name="remove">If set to <c>true</c> items will be removes and re-inserted.</param>
/// <returns>true if successful.</returns>
public static bool TrySwap(this IList list, int indexA, int indexB, bool remove)
{
try
{
Swap(list, indexA, indexB, remove);
}
catch
{
return false;
}
return true;
}
}
}