Skip to content

IEnumerable Extensions

Shmellyorc edited this page Aug 31, 2026 · 1 revision

IEnumerableExtensions provides a comprehensive set of extension methods for working with sequences, including validation, iteration, random selection, partitioning, shuffling, and more.


Overview

Feature Description
Validation Check if a sequence is empty or not empty
Iteration Perform an action on each element
Random Selection Get a random element or sample from a sequence
Safe Access Get an element by index with fallback
Search Find the index of an element
Partitioning Split a sequence into two groups
Shuffling Randomize the order of elements
Distinct Get distinct elements by a key
Filtering Filter out null elements

Validation

IsEmpty

Determines whether the sequence is null or empty.

var items = new List<int> { 1, 2, 3 };
bool empty = items.IsEmpty();  // false

var emptyList = new List<int>();
bool empty2 = emptyList.IsEmpty();  // true

var nullList = (List<int>)null;
bool empty3 = nullList.IsEmpty();  // true

IsNotEmpty

Determines whether the sequence is not null and not empty.

var items = new List<int> { 1, 2, 3 };
bool notEmpty = items.IsNotEmpty();  // true

Iteration

ForEach

Performs the specified action on each element of the sequence.

var items = new List<int> { 1, 2, 3, 4, 5 };
items.ForEach(x => Console.WriteLine(x));

// With complex logic
items.ForEach(x =>
{
    if (x % 2 == 0)
        Console.WriteLine($"{x} is even");
});

Random Selection

Random

Gets a random element from the sequence.

var items = new List<string> { "apple", "banana", "cherry" };
string random = items.Random();  // Returns a random element

// With a specific random instance
var customRandom = new FastRandom(42);
string random2 = items.Random(customRandom);

RandomSample

Gets a random sample of the specified size from the sequence.

var items = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var sample = items.RandomSample(3);  // Returns 3 random elements

Safe Access

SafeElementAt

Safely gets the element at the specified index, returning default if out of range.

var items = new List<string> { "a", "b", "c" };

string value = items.SafeElementAt(1);   // "b"
string notFound = items.SafeElementAt(10); // null (default)

Search

IndexOf

Finds the index of the first occurrence of the specified item.

var items = new List<string> { "apple", "banana", "cherry", "banana" };
int index = items.IndexOf("banana");  // 1
int notFound = items.IndexOf("grape"); // -1

Partitioning

Partition

Partitions the sequence into two lists based on a predicate.

var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var (evens, odds) = numbers.Partition(x => x % 2 == 0);

// evens: [2, 4, 6, 8, 10]
// odds: [1, 3, 5, 7, 9]

Shuffling

Shuffle

Shuffles the sequence using the Fisher-Yates algorithm.

var items = new List<int> { 1, 2, 3, 4, 5 };
var shuffled = items.Shuffle();  // Random order, e.g., [3, 1, 5, 2, 4]

Distinct

DistinctBy

Returns distinct elements from a sequence based on a key selector.

var people = new List<(string Name, int Age)>
{
    ("Alice", 25),
    ("Bob", 30),
    ("Alice", 25),
    ("Charlie", 35)
};

var distinct = people.DistinctBy(p => p.Name);
// Returns: ("Alice", 25), ("Bob", 30), ("Charlie", 35)

AllDistinct

Determines whether all elements in the sequence are distinct.

var items = new List<int> { 1, 2, 3, 4, 5 };
bool allDistinct = items.AllDistinct();  // true

var duplicates = new List<int> { 1, 2, 2, 3, 4 };
bool allDistinct2 = duplicates.AllDistinct();  // false

Filtering

NotNull (Reference Types)

Filters out null elements from a sequence of reference types.

var items = new List<string> { "a", null, "b", null, "c" };
var nonNull = items.NotNull();  // ["a", "b", "c"]

NotNull (Nullable Value Types)

Filters out null values from a sequence of nullable value types.

var items = new List<int?> { 1, null, 2, null, 3 };
var nonNull = items.NotNull();  // [1, 2, 3]

Examples

Random Enemy Spawning

public Enemy SpawnRandomEnemy()
{
    var enemyTypes = new List<Type> { typeof(Goblin), typeof(Orc), typeof(Troll) };
    var enemyType = enemyTypes.Random();
    return Activator.CreateInstance(enemyType) as Enemy;
}

Filter and Process

public void ProcessActiveEntities()
{
    var entities = _entityManager.GetAllEntities();
    
    // Filter out inactive entities and process the rest
    entities
        .Where(e => e.IsActive)
        .ForEach(e => e.Update());
}

Shuffle Deck

public void ShuffleDeck()
{
    var deck = new List<Card>();
    // ... populate deck ...
    
    deck = deck.Shuffle();
}

Partition Inventory

public void OrganizeInventory()
{
    var items = _inventory.GetAllItems();
    var (weapons, nonWeapons) = items.Partition(i => i is Weapon);
    
    // weapons contains all Weapon items
    // nonWeapons contains all other items
}

Safe Array Access

public T GetTile<T>(List<T> tiles, int x, int y, int width)
{
    int index = y * width + x;
    return tiles.SafeElementAt(index);
}

Random Sample for Loot

public List<Item> GetRandomLoot(int count)
{
    var allItems = _itemDatabase.GetAllItems();
    return allItems.RandomSample(count);
}

Summary

Method Description
IsEmpty Checks if the sequence is null or empty
IsNotEmpty Checks if the sequence is not null and not empty
ForEach Performs an action on each element
Random Gets a random element from the sequence
RandomSample Gets a random sample of elements
SafeElementAt Gets an element by index with fallback
IndexOf Finds the index of an element
Partition Splits the sequence into two groups
Shuffle Randomizes the order of elements
DistinctBy Gets distinct elements by a key
AllDistinct Checks if all elements are distinct
NotNull Filters out null elements

Back to Home

Clone this wiki locally