Skip to content

IList Extensions

Andrzej Kebab edited this page Feb 4, 2024 · 6 revisions

UtilityLibrary.Core

LastIndex

Returns the last index of the list.

List<T> list = // initialize your List<T>
int lastIndex = IListExtensions.LastIndex(list);

Parameters:

  • list: The list for which the last index is retrieved.

Returns:

  • lastIndex: The last index of the list.

IsNullOrEmpty

Checks if the IList is null or empty.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list1 = new List<int>();
List<int> list2 = null;

bool isNullOrEmpty1 = list1.IsNullOrEmpty();
bool isNullOrEmpty2 = list2.IsNullOrEmpty();

// Result: isNullOrEmpty1 = true, isNullOrEmpty2 = true

IsEmpty

Checks if the IList is empty, throwing an exception if it is null.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int>();

bool isEmpty = list.IsEmpty();

// Result: isEmpty = true

Swap

Swaps the elements at the specified indices in the list.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3, 4, 5 };

list.Swap(1, 3);

// Result: list = [1, 4, 3, 2, 5]

AddAt

Adds an element to the specified index of the list. If the index is out of bounds, the element is added to the end of the list.

IList<T> list = // initialize your IList<T>
int index = // specify the index
T element = // specify the element
list.AddAt(index, element);

Parameters:

  • list: The list to which the element is added.
  • index: The index at which the element should be added.
  • element: The element to add to the list.

AddUnique

Adds an item to the list if it is not already present.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3 };

bool added = list.AddUnique(4);

// Result: added = true, list = [1, 2, 3, 4]

InsertUnique

Inserts an item into the list at the specified index, if it is not already present.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3 };

bool inserted = list.InsertUnique(1, 4);

// Result: inserted = true, list = [1, 4, 2, 3]

InsertRangeUnique

Inserts a range of items into the list at the specified index, skipping any items that are already present.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3 };

int count = list.InsertRangeUnique(1, new List<int> { 4, 5, 2 });

// Result: count = 2, list = [1, 4, 5, 2, 3]

TryGetValue

Tries to get a value from the list.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3 };

int value = list.TryGetValue(2);

// Result: value = 2

GetAndRemove

Gets a value from the list and removes it.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3 };

int value = list.GetAndRemove(2);

// Result: value = 2, list = [1, 3]

GetAtWrapped

Retrieves the element at the specified index in a list, with wrapping for out-of-bounds indices.

List<T> list = // initialize your List<T>
int index = // specify the index
T result = IListExtensions.GetAtWrapped(list, index);

Parameters:

  • list: The list from which to retrieve the element.
  • index: The index at which to retrieve the element. Negative indices wrap around from the end of the list.

Returns:

  • result: The element at the specified index with wrapping for out-of-bounds indices.

GetRandomItem

Retrieves a random element from a list.

IList<T> list = // initialize your IList<T>
T randomItem = IListExtensions.GetRandomItem(list);

Parameters:

  • list: The list from which to retrieve a random element.

Returns:

  • randomItem: A random element from the list.

Before

Gets the item before the specified item in the list.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3 };

int before = list.Before(2);

// Result: before = 1

After

Gets the item after the specified item in the list.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3 };

int after = list.After(2);

// Result: after = 3

Find

Finds the first item in the list that matches the specified predicate.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3, 4, 5 };

int found = list.Find(x => x % 2 == 0);

// Result: found = 2

FindAll

Finds all items in the list that match the specified predicate.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3, 4, 5 };

List<int> foundAll = list.FindAll(x => x % 2 == 0);

// Result: foundAll = [2, 4]

MoveUp / MoveDown

Moves an item up or down in the list by a specified number of steps.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3, 4, 5 };

list.MoveUp(3, 2);

// Result: list = [1, 3,

 4, 2, 5]

list.MoveDown(3, 2);

// Result: list = [1, 4, 2, 3, 5]

RemoveLast

Removes the last element from the list if the list is not empty.

IList<T> list = // initialize your IList<T>
list.RemoveLast();

Parameters:

  • list: The list from which to remove the last element.

RemoveRandomItem

Removes a random element from a list and returns it.

IList<T> list = // initialize your IList<T>
T removedItem = list.RemoveRandomItem();

Parameters:

  • list: The list from which to remove a random element.

Returns:

  • removedItem: The removed random element.

RemoveStartRepeat

Removes repeated items from the start of the list.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 1, 2, 3, 4 };

list.RemoveStartRepeat();

// Result: list = [2, 3, 4]

RemoveEndRepeat

Removes repeated items from the end of the list.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3, 4, 4 };

list.RemoveEndRepeat();

// Result: list = [1, 2, 3]

Distinct

Removes duplicate items from the list.

using UtilityLibrary.Core;
using System;
using System.Collections.Generic;

List<int> list = new List<int> { 1, 2, 3, 2, 4, 5, 4 };

list.Distinct();

// Result: list = [1, 2, 3, 4, 5]

Clone

Creates a new list that is a copy of the original list.

IList<T> originalList = // initialize your IList<T>
List<T> clonedList = originalList.Clone();

Parameters:

  • originalList: The original list to be copied.

Returns:

  • clonedList: A new list that is a copy of the original list.

Shuffle

Shuffles the elements of a list using the Fisher-Yates algorithm.

IList<T> list = // initialize your IList<T>
list.Shuffle();

Parameters:

  • list: The list to be shuffled.

UtilityLibrary.Core.LinqReplacement

First

Returns the first element of a list, or a default value if the list is null or empty.

using UtilityLibrary.Core.LinqReplacement;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

int firstNumber = numbers.First();

// Result: 1

First with Predicate

Returns the first element of a list that satisfies a specified condition, or a default value if no such element is found.

using UtilityLibrary.Core.LinqReplacement;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

int firstEvenNumber = numbers.First(x => x % 2 == 0);

// Result: 2

First (with Count)

Returns a specified number of contiguous elements from the start of a list, optionally filtering the elements with a predicate.

using UtilityLibrary.Core.LinqReplacement;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

List<int> firstThreeNumbers = numbers.First(3);

// Result: [1, 2, 3]

Last

Returns the last element of a list, or a default value if the list is null or empty.

using UtilityLibrary.Core.LinqReplacement;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

int lastNumber = numbers.Last();

// Result: 5

Last with Predicate

Returns the last element of a list that satisfies a specified condition, or a default value if no such element is found.

using UtilityLibrary.Core.LinqReplacement;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

int lastOddNumber = numbers.Last(x => x % 2 != 0);

// Result: 5

Last (with Count)

Returns a specified number of contiguous elements from the end of a list, optionally filtering the elements with a predicate.

using UtilityLibrary.Core.LinqReplacement;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

List<int> lastTwoNumbers = numbers.Last(2);

// Result: [4, 5]

Contains with Predicate

Determines whether a list contains elements that satisfy a specified condition.

using UtilityLibrary.Core.LinqReplacement;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

bool containsEvenNumber = numbers.Contains(x => x % 2 == 0);

// Result: true

Random

Random(this IList list)

Returns a random item from the list.

// Example usage
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var randomItem = numbers.Random();
Console.WriteLine($"Random item: {randomItem}");

Parameters:

  • list (IList<T>): The list to get a random item from.

Returns:

  • T: A random item from the list, or the default value for the type if the list is empty.

Random(this IList list, Predicate predicate)

Returns a random item from the list that matches a predicate.

// Example usage with a predicate
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var randomEvenNumber = numbers.Random(x => x % 2 == 0);
Console.WriteLine($"Random even number: {randomEvenNumber}");

Parameters:

  • list (IList<T>): The list to get a random item from.
  • predicate (Predicate<T>): A function to test each item for a condition.

Returns:

  • T: A random item from the list that matches the predicate, or the default value for the type if no items match the predicate.

Random(this IList list, int count, bool allowRepeat = false)

Returns a specified number of random items from the list.

// Example usage with count and disallowing repeats
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var randomNumbers = numbers.Random(3, allowRepeat: false);
Console.WriteLine($"Random numbers: {string.Join(", ", randomNumbers)}");

Parameters:

  • list (IList<T>): The list to get random items from.
  • count (int): The number of random items to get.
  • allowRepeat (bool): Whether to allow the same item to be chosen more than once.

Returns:

  • List&lt;T&gt;: A list of random items from the list.

Random(this IList list, Func<T, int> weightGetter)

Returns a random item from the list, with the probability of choosing each item proportional to its weight.

// Example usage with weights
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
var randomFruit = fruits.Random(fruit => fruit.Length);
Console.WriteLine($"Random fruit: {randomFruit}");

Parameters:

  • list (IList<T>): The list to get a random item from.
  • weightGetter (Func<T, int>): A function to get the weight of each item.

Returns:

  • T: A random item from the list, chosen with probability proportional to its weight.

Random(this IList list, Func<T, float> weightGetter, int count)

Returns a specified number of random items from the list, with the probability of choosing each item proportional to its weight.

// Example usage with weights and count
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
var randomFruits = fruits.Random(fruit => fruit.Length, count: 2);
Console.WriteLine($"Random fruits: {string.Join(", ", randomFruits)}");

Parameters:

  • list (IList;): The list to get random items from.
  • weightGetter (Func<T, float>): A function to get the weight of each item.
  • count (int): The number of random items to get.

Returns:

  • List<T>: A list of random items from the list, chosen with probability proportional to their weights.

Min / Max

Min

Returns the minimum item in the list based on the IComparable interface.

// Example usage
List<int> myList = /* Instantiate or reference a list of integers */;
int minValue = myList.Min();
Debug.Log($"Minimum value in the list: {minValue}");

Parameters:

  • list (IList<T>): The list to find the minimum item in.

Returns:

  • T: The item with the minimum value in the list.

Max

Returns the maximum item in the list based on the IComparable interface.

// Example usage
List<int> myList = /* Instantiate or reference a list of integers */;
int maxValue = myList.Max();
Debug.Log($"Maximum value in the list: {maxValue}");

Parameters:

  • list (IList<T>): The list to find the maximum item in.

Returns:

  • T: The item with the maximum value in the list.

Custom Comparisons

Both Min and Max methods also support custom comparisons by providing a key selector function.

// Example usage with custom comparison
List<string> stringList = /* Instantiate or reference a list of strings */;
string minLengthString = stringList.Min(str => str.Length);
Debug.Log($"String with minimum length: {minLengthString}");

Parameters:

  • list (List<T>): The list to find the minimum or maximum item in.
  • keyGetter (Func<T, IComparable>): A function to extract the comparison key from each element.

Returns:

  • T: The item with the minimum or maximum value in the list based on the provided key.

To List

ToList

Converts the elements of an IList to another type and returns a List containing the converted elements.

// Example usage
List<double> doubleList = /* Instantiate or reference a list of doubles */;
List<int> intList = doubleList.ToList(d => (int)d);
Debug.Log($"Converted list of doubles to integers: {string.Join(", ", intList)}");

Parameters:

  • list (IList<T>): The list to convert.
  • selector (Func<T, TResult>): A transform function to apply to each element.

Returns:

  • List<TResult>: A List of TResult whose elements are the result of invoking the transform function on each element of the source list.

To Dictionary

ToDictionary

Converts the elements of an IList to a Dictionary using a provided key selector function.

// Example usage
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Person> personList = /* Instantiate or reference a list of Person objects */;
Dictionary<string, Person> nameToPersonDict = personList.ToDictionary(p => p.Name);
Debug.Log($"Created a dictionary mapping names to Person objects: {nameToPersonDict}");

Parameters:

  • list (IList<T>): The list to convert.
  • getKeyFunc (Func<T, TKey>): A function to extract a key from each element.

Returns:

  • Dictionary<TKey, T>: A Dictionary of TKey and T whose elements are the result of invoking the key selector function on each element of the source list.

ToDictionary (with Key and Value Selectors)

Converts the elements of an IList to a Dictionary using provided key and value selector functions.

// Example usage
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Person> personList = /* Instantiate or reference a list of Person objects */;
Dictionary<string, int> nameToAgeDict = personList.ToDictionary(p => p.Name, p => p.Age);
Debug.Log($"Created a dictionary mapping names to ages: {nameToAgeDict}");

Parameters:

  • list (IList<T>): The list to convert.
  • getKeyFunc (Func<T, TKey>): A function to extract a key from each element.
  • getValueFunc (Func<T, TValue>): A function to extract a value from each element.

Returns:

  • Dictionary<TKey, TValue>: A Dictionary of TKey and TValue whose elements are the result of invoking the key and value selector functions on each element of the source list.

Clone this wiki locally