A simple and lightweight implementation of a non-empty list in C#, inspired by Scala's List, that ensures a collection always has at least one item. This helps in reducing null-related bugs and ensures safe operations on collections with at least one element.
If you like or are using this project please give it a star. Thanks!
- Non-Empty Guarantee: Always contains at least one element
- Head/Tail Access: Convenient
Head,Tail,Init,First, andLastproperties - Functional Operations:
Map,FlatMap,Reduce,Fold,Zip,Partition, and more - Pattern Matching:
Matchmethod and deconstruction support - Async Support: Full async extension methods for all operations
- Immutable Variant:
ImmutableNonEmptyList<T>for thread-safe scenarios - JSON Serialization: Built-in System.Text.Json support
- EF Core Integration: Entity Framework Core support via separate package
- Equality Support: Implements
IEquatable<T>with==and!=operators - Multi-targeting: Supports .NET 6.0 and .NET 8.0
dotnet add package Masterly.NonEmptyListOr via Package Manager Console:
Install-Package Masterly.NonEmptyList
using Masterly.NonEmptyList;
// Create a NonEmptyList - guaranteed to have at least one element
NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);
Console.WriteLine(numbers.Head); // 1
Console.WriteLine(numbers.Last); // 5
Console.WriteLine(numbers.Tail); // [2, 3, 4, 5]
// Functional operations
NonEmptyList<string> strings = numbers.Map(x => x.ToString());
int sum = numbers.Reduce((a, b) => a + b);
// Pattern matching
string result = numbers.Match(
single: x => $"Just {x}",
multiple: (head, tail) => $"Head: {head}, Count: {tail.Count + 1}"
);
// Safe from empty collection errors
int first = numbers.Head; // Always safe - no exceptions!For comprehensive documentation, see the Wiki.
| Topic | Description |
|---|---|
| Getting Started | Installation and basic usage |
| Core Concepts | Head, Tail, and properties |
| Creating NonEmptyList | Constructors and factory methods |
| Functional Operations | Map, FlatMap, Reduce, Fold, Zip |
| Pattern Matching | Match and deconstruction |
| Collection Operations | Concat, Reverse, Sliding, Chunks |
| Async Operations | MapAsync, FilterAsync, FoldAsync |
| ImmutableNonEmptyList | Thread-safe immutable variant |
| JSON Serialization | System.Text.Json support |
| EF Core Integration | Entity Framework Core support |
For Entity Framework Core support, install the separate package:
dotnet add package Masterly.NonEmptyList.EntityFrameworkCore// Store NonEmptyList as JSON
modelBuilder.Entity<Product>()
.Property(p => p.Tags)
.HasNonEmptyListConversion();
// Configure relationships
modelBuilder.Entity<Order>()
.HasNonEmptyManyWithOne(o => o.Items, i => i.Order);See the EF Core Integration wiki page for full documentation.
MIT
Free Software, Hell Yeah!
