Skip to content

Instantly share code, notes, and snippets.

@rje
Created January 30, 2015 17:37
Show Gist options
  • Save rje/8e7ae8ee79518a6e6125 to your computer and use it in GitHub Desktop.
Save rje/8e7ae8ee79518a6e6125 to your computer and use it in GitHub Desktop.
Things I do a lot with lists
// Things I do a lot with lists:
// Creation
var list = new List<GameObject>();
// Lists resize dynamically as you add content, but if
// you roughly know how many elements you plan on having
// you can specify a capacity on creation
list = new List<GameObject>(200);
// You can also specify specific values at creation time if you like
var obj1 = new GameObject();
var obj2 = new GameObject();
list = new List<GameObject>() { obj1, obj2 };
// Adding elements:
var go = new GameObject();
list.Add(go);
// You can also merge two lists by using add range
var obj3 = new GameObject();
var obj4 = new GameObject();
var toAdd = new List<GameObject>() { obj3, obj4 };
list.AddRange(toAdd);
// Insert at a specific position
list.Insert(1, new GameObject());
// You can also merge a list in at a specific position
list.InsertRange(1, toAdd);
// Check to see if a list has an object
var result = list.Contains(obj3); // result = true
result = list.Contains(new GameObject()); // result = false
// Get index of an item in the list
var idx = list.IndexOf(obj3);
// Remove an object by index
list.RemoveAt(3);
// Remove a specific object when index is unknown
list.Remove(obj3);
// Remove all objects that match a predicate
// (look up System.Predicate<T> for more info)
list.RemoveAll((toCheck) =>
{
return toCheck.name.Equals("obj-to-remove");
});
// Sort a list based on a comparator
// (look up System.Comparison<T> for more info)
// This will sort the list by gameObject.name
list.Sort((a, b) =>
{
return a.name.CompareTo(b.name);
});
// Clear the list
list.Clear();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment