Skip to content

Instantly share code, notes, and snippets.

@MattRix
Created May 1, 2016 14:50
Show Gist options
  • Select an option

  • Save MattRix/c757899f656176eddeae49cfe53580c9 to your computer and use it in GitHub Desktop.

Select an option

Save MattRix/c757899f656176eddeae49cfe53580c9 to your computer and use it in GitHub Desktop.
Extension methods for easily reordering an item in a list.
using UnityEngine;
using System;
using System.Collections.Generic;
public static class RXListReordering
{
public static bool CanReorder<T>(this List<T> items, T item, int dir)
{
var index = items.IndexOf(item);
if(index == -1) return false;
var newIndex = Mathf.Clamp(index + dir, 0, items.Count-1);
return (index != newIndex);
}
public static bool Reorder<T>(this List<T> items, T item, int dir)
{
var index = items.IndexOf(item);
var newIndex = Mathf.Clamp(index + dir, 0, items.Count-1);
if(index != newIndex) //did index change
{
items.RemoveAt(index); //remove the item from its previous location
if(newIndex > index) index++; //because the indices will change
items.Insert(newIndex,item);
return true;
}
else
{
return false;
}
}
}
@MattRix

MattRix commented May 1, 2016

Copy link
Copy Markdown
Author

Usage:
myList.Reorder(someItem,-1) to move an item up,
myList.Reorder(someItem,1) to move an item down.

Use myList.CanReorder(someItem, -1) to find out if you can move an item upwards.
Use myList.CanReorder(someItem, 1) to find out if you can move an item downwards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment