Skip to content

Conversion Methods

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

Conversion Methods

NonEmptyList<T> provides methods to convert to various .NET collection types.

ToArray

Convert to a standard array:

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

ToHashSet

Convert to a HashSet (removes duplicates):

NonEmptyList<int> list = new(1, 2, 2, 3, 3);
HashSet<int> set = list.ToHashSet();
// Result: {1, 2, 3}

ToDictionary

Convert to a Dictionary using a key selector:

NonEmptyList<string> words = new("apple", "banana", "cherry");
Dictionary<char, string> dict = words.ToDictionary(w => w[0]);
// Result: {'a': "apple", 'b': "banana", 'c': "cherry"}

With both key and value selectors:

NonEmptyList<string> words = new("apple", "banana");
Dictionary<char, int> dict = words.ToDictionary(
    w => w[0],           // Key selector
    w => w.Length        // Value selector
);
// Result: {'a': 5, 'b': 6}

ToQueue

Convert to a Queue (FIFO):

NonEmptyList<int> list = new(1, 2, 3);
Queue<int> queue = list.ToQueue();

int first = queue.Dequeue(); // 1
int second = queue.Dequeue(); // 2

ToStack

Convert to a Stack (LIFO):

NonEmptyList<int> list = new(1, 2, 3);
Stack<int> stack = list.ToStack();

int top = stack.Pop(); // 3
int next = stack.Pop(); // 2

ToLinkedList

Convert to a LinkedList:

NonEmptyList<int> list = new(1, 2, 3);
LinkedList<int> linked = list.ToLinkedList();

AsReadOnly

Get a read-only view:

NonEmptyList<int> list = new(1, 2, 3);
IReadOnlyList<int> readOnly = list.AsReadOnly();

ToImmutable

Convert to an immutable variant:

NonEmptyList<int> mutable = new(1, 2, 3);
ImmutableNonEmptyList<int> immutable = mutable.ToImmutable();

Next Steps

Clone this wiki locally