-
Notifications
You must be signed in to change notification settings - Fork 0
Utility Methods
Ahmad Al-freihat edited this page Jan 1, 2026
·
1 revision
NonEmptyList<T> provides various utility methods for common operations.
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 5Since the list is never empty, Random() is always safe to call.
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"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"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: cherryNonEmptyList<Product> products = GetProducts();
Product cheapest = products.MinBy(p => p.Price);
Product mostExpensive = products.MaxBy(p => p.Price);
Product heaviest = products.MaxBy(p => p.Weight);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);NonEmptyList<Task> tasks = GetTasks();
tasks.ForEachWithIndex((task, index) =>
{
Console.WriteLine($"Processing task {index + 1} of {tasks.Count}");
ProcessTask(task);
});- Learn about Validation methods for data validation
- Explore Async Operations for asynchronous processing