Skip to content

Utility Methods

Ahmad Al-freihat edited this page Jan 1, 2026 · 1 revision

Utility Methods

NonEmptyList<T> provides various utility methods for common operations.

Random

Get a random element from the list:

NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);
int random = numbers.Random();
// Returns one of: 1, 2, 3, 4, or 5

Since the list is never empty, Random() is always safe to call.

MinBy

Find the element with the minimum value by a key:

NonEmptyList<string> words = new("hi", "hello", "hey");
string shortest = words.MinBy(w => w.Length);
// Result: "hi"

MaxBy

Find the element with the maximum value by a key:

NonEmptyList<string> words = new("hi", "hello", "hey");
string longest = words.MaxBy(w => w.Length);
// Result: "hello"

ForEachWithIndex

Iterate with element and index:

NonEmptyList<string> words = new("apple", "banana", "cherry");
words.ForEachWithIndex((item, index) =>
    Console.WriteLine($"{index}: {item}")
);
// Output:
// 0: apple
// 1: banana
// 2: cherry

Practical Examples

Finding Extremes

NonEmptyList<Product> products = GetProducts();

Product cheapest = products.MinBy(p => p.Price);
Product mostExpensive = products.MaxBy(p => p.Price);
Product heaviest = products.MaxBy(p => p.Weight);

Random Selection

NonEmptyList<string> quotes = new(
    "Hello, World!",
    "Code is poetry",
    "Keep it simple"
);

// Display a random quote - always safe since NonEmptyList is never empty
string dailyQuote = quotes.Random();
Console.WriteLine(dailyQuote);

Processing with Index

NonEmptyList<Task> tasks = GetTasks();
tasks.ForEachWithIndex((task, index) =>
{
    Console.WriteLine($"Processing task {index + 1} of {tasks.Count}");
    ProcessTask(task);
});

Next Steps

Clone this wiki locally