Created
May 1, 2016 14:50
-
-
Save MattRix/c757899f656176eddeae49cfe53580c9 to your computer and use it in GitHub Desktop.
Extension methods for easily reordering an item in a list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.