add extension method to move an item within an collection

This commit is contained in:
Pascal Schedel
2024-10-21 09:22:02 +02:00
parent 34c4f1c727
commit 547359ecf3

View File

@@ -0,0 +1,30 @@
namespace Pilz.Extensions.Collections;
public static class IListExtensions
{
public static bool Move<T>(this IList<T> @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;
}
}