Skip to content

Collection Operations

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

Collection Operations

NonEmptyList<T> provides a rich set of operations for manipulating and combining lists.

Concatenation

Combine two NonEmptyLists:

NonEmptyList<int> list1 = new(1, 2);
NonEmptyList<int> list2 = new(3, 4);

NonEmptyList<int> combined = list1.Concat(list2);
// Result: [1, 2, 3, 4]

Prepend

Add an element at the beginning:

NonEmptyList<int> list = new(2, 3);
list.Prepend(1);
// Result: [1, 2, 3]

Reverse

Reverse the order of elements:

NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);
NonEmptyList<int> reversed = numbers.ReverseList();
// Result: [5, 4, 3, 2, 1]

Distinct

Remove duplicate elements:

NonEmptyList<int> numbers = new(3, 1, 2, 1, 3);
NonEmptyList<int> distinct = numbers.DistinctList();
// Result: [3, 1, 2]

DistinctBy

Remove duplicates based on a key:

NonEmptyList<string> words = new("apple", "apricot", "banana", "blueberry");
NonEmptyList<string> distinctByFirst = words.DistinctBy(w => w[0]);
// Result: ["apple", "banana"]

Take and Skip

TakeNonEmpty

Take the first N elements (returns null if not enough elements):

NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);
NonEmptyList<int>? first2 = numbers.TakeNonEmpty(2);
// Result: [1, 2]

SkipNonEmpty

Skip the first N elements (returns null if nothing left):

NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);
NonEmptyList<int>? skip2 = numbers.SkipNonEmpty(2);
// Result: [3, 4, 5]

TakeAtLeastOne

Take N elements, but always return at least one:

NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);
NonEmptyList<int> atLeast = numbers.TakeAtLeastOne(0);
// Result: [1] (ensures at least 1)

Sliding Windows

Create overlapping windows of elements:

NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);

// Default sliding window
IEnumerable<NonEmptyList<int>> windows = numbers.Sliding(3);
// Result: [[1,2,3], [2,3,4], [3,4,5]]

// With step
IEnumerable<NonEmptyList<int>> windowsStep2 = numbers.Sliding(2, step: 2);
// Result: [[1,2], [3,4]]

Chunks

Split into non-overlapping chunks:

NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);
IEnumerable<NonEmptyList<int>> chunks = numbers.ChunkNonEmpty(2);
// Result: [[1,2], [3,4], [5]]

Intersperse

Insert a separator between elements:

NonEmptyList<int> numbers = new(1, 2, 3);
NonEmptyList<int> interspersed = numbers.Intersperse(0);
// Result: [1, 0, 2, 0, 3]

Rotate

Rotate elements left or right:

NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);

NonEmptyList<int> rotatedLeft = numbers.RotateLeft(1);
// Result: [2, 3, 4, 5, 1]

NonEmptyList<int> rotatedRight = numbers.RotateRight(1);
// Result: [5, 1, 2, 3, 4]

Next Steps

Clone this wiki locally