add extension method to move an item within an collection
This commit is contained in:
30
Pilz.Extensions/Collections/IListExtensions.cs
Normal file
30
Pilz.Extensions/Collections/IListExtensions.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user