diff --git a/Pilz.Extensions/Collections/IListExtensions.cs b/Pilz.Extensions/Collections/IListExtensions.cs new file mode 100644 index 0000000..1964bbd --- /dev/null +++ b/Pilz.Extensions/Collections/IListExtensions.cs @@ -0,0 +1,30 @@ +namespace Pilz.Extensions.Collections; + +public static class IListExtensions +{ + public static bool Move(this IList @this, T item, int amount) + { + var oldIndex = @this.IndexOf(item); + + if (oldIndex == -1) + return false; + + var newIndex = oldIndex + amount; + + if (newIndex < 0) + newIndex = 0; + else if (newIndex >= @this.Count) + newIndex = @this.Count; + + if (newIndex == oldIndex) + return false; + + if (newIndex > 0 && newIndex > oldIndex) + newIndex -= 1; + + @this.RemoveAt(oldIndex); + @this.Insert(newIndex, item); + + return true; + } +}