Created
March 4, 2013 21:37
-
-
Save michaelbartnett/5085908 to your computer and use it in GitHub Desktop.
Useful IList Extensions for C#/.Net
This file contains 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 System; | |
using System.Collections.Generic; | |
public static class ListExtensions | |
{ | |
public static TList Populate<TList, TElem>(this TList list, TElem defaultValue) where TList : IList<TElem> | |
{ | |
for (int i = 0; i < list.Count; i++) { | |
list[i] = defaultValue; | |
} | |
return list; | |
} | |
public static TList KnuthShuffle<TList>(this TList list) where TList : IList | |
{ | |
for (int i = list.Count - 1; i > 0; i--) | |
{ | |
int n = Random.Range(0, i); | |
list.Swap(i, n); | |
} | |
return list; | |
} | |
public static void Swap<T>(this T list, int i1, int i2) where T : IList | |
{ | |
var temp = list[i1]; | |
list[i1] = list[i2]; | |
list[i2] = temp; | |
} | |
public static T GetClamped<T>(this IList<T> list, int index) | |
{ | |
if (index >= list.Count) { | |
index = list.Count - 1; | |
} else if (index < 0) { | |
index = 0; | |
} | |
return list[index]; | |
} | |
public static int WrapIndex<T>(this IList<T> list, int index) | |
{ | |
int len = list.Count; | |
return ((index % len) + len) % len; | |
} | |
public static T GetWrapped<T>(this IList<T> list, int index) | |
{ | |
return list[list.WrapIndex(index)]; | |
} | |
public static T GetWrapped<T>(this IList<T> list, ref int index) | |
{ | |
index = list.WrapIndex(index); | |
return list[index]; | |
} | |
public static T Pop<T>(this List<T> list) | |
{ | |
int lastIndex = list.Count - 1; | |
T top = list[lastIndex]; | |
list.RemoveAt(lastIndex); | |
return top; | |
} | |
public static T SwapAndPop<T>(this List<T> list, int indexToRemove) | |
{ | |
list.Swap(indexToRemove, list.Count - 1); | |
return list.Pop(); | |
} | |
public static T SwapAndPop<T>(this List<T> list, T item) | |
{ | |
int indexToRemove = list.IndexOf(item); | |
return list.SwapAndPop(indexToRemove); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment