Collections
- Creating Collections
- Complete Example: Collection Report
- Keys and Return Values
- Available Methods
- Callbacks and Comparisons
- Grouping and Plucking
- Mutating a Collection
- Macros and Higher Order Messages
- Lazy Collections
- Model Collections
DotBlaze.Support.Collection<T> is an ordered, keyed collection with the operations documented for Laravel 13 collections. It implements IEnumerable<T>: foreach enumerates values, and LINQ remains available.
var totals = Collect(orders)
.Where(o => o.Paid)
.GroupBy(o => o.CustomerId)
.Map((group, key) => new { Customer = key, Total = group.Sum(o => o.Amount) })
.SortByDesc(x => x.Total)
.Take(10);Most transformations return a new collection. The original is changed only by mutating methods such as Push, Put, Forget, and Transform.
Complete Example: Collection Report
This Blog command declares all its input data. It filters without mutating the original and resets keys before JSON output:
// app/Commands/CollectionDemo.cs
using DotBlaze;
using static DotBlaze.Support.Functions;
namespace Blog.Commands;
public class CollectionDemo : Command
{
public override string Signature => "demo:collection";
public override Task<int> Handle()
{
var original = Collect(new[] { 10, 20, 30 });
var report = original.Filter(value => value >= 20)
.Map(value => value * 2).Values();
if (original.Count != 3 || report.ToJson() != "[40,60]")
throw new InvalidOperationException("Unexpected collection report.");
Line(report.ToJson());
return Task.FromResult(0);
}
}Run dotblaze demo:collection; expected output: [40,60]. Without Values(), filtered numeric keys can produce a JSON object instead of an array. For large database datasets, apply query predicates before Get() rather than loading all rows merely to filter a collection.
Creating Collections
The application template imports DotBlaze.Support and DotBlaze.Support.Functions globally.
var numbers = Collect(new[] { 1, 2, 3 });
var empty = Collect();
var users = new Collection<User>(list);
var settings = Collect(new Dictionary<string, object?>
{
["name"] = "Blog",
["debug"] = false,
});
var decoded = Collection.FromJson("""{"name":"Blog","roles":["admin"]}""");
var range = Collection.Range(1, 5); // 1, 2, 3, 4, 5
var squares = Collection.Times(3, n => n * n); // 1, 4, 9
var wrapped = Collection.Wrap("hello"); // one itemUse Collection.Make(value) for a value whose shape is known only at runtime, Collection.Wrap(value) to wrap a scalar, and Collection.Unwrap(value) to get a collection's underlying array/dictionary representation. Wrapping null makes an empty collection.
Keys and Return Values
Collections retain integer and string keys. Pairs() enumerates key/value pairs; callbacks may accept (value, key). Numeric string keys such as "1" and integer keys such as 1 identify the same entry, while "01" remains a string. Assigning an existing key replaces its value without moving its position.
var selected = Collect(new[] { 10, 20, 30 }).Filter(n => n >= 20);
selected.ToJson(); // {"1":20,"2":30}
selected.Values().ToJson(); // [20,30]
selected.Keys(); // 1, 2
selected.Get(1); // 20
selected.Get("missing"); // nullGet, First, Last, Before, After, Value, Min, and Max have object-backed dynamic results. This allows an empty Collection<int> to return null instead of 0. FirstOrFail and Sole return T; they throw ItemNotFoundException when nothing matches. Sole throws MultipleItemsFoundException when more than one item matches.
var first = numbers.First(n => n > 10); // null
var fallback = numbers.First(n => n > 10, 99); // 99
var setting = settings.Get("timezone", () => "UTC");
User user = users.FirstOrFail(u => u.Active);Count is a property. All() returns an object?[] for consecutive zero-based keys, or a dictionary for other keys. ToArray() also recursively converts nested collections. ToJson() and ToPrettyJson() preserve this array/object distinction, as does System.Text.Json serialization. Use LINQ's ToList() when you need a typed List<T>.
Search returns the matching key or false. A key of 0 is a successful result.
Available Methods
These are the Laravel collection operations, using C# casing and delegates. Property selectors use dot paths through dictionaries, collections, and public object members; direct collection-key access uses literal keys.
| Area | Methods |
|---|---|
| Creation | Make, Wrap, Unwrap, Range, Times, FromJson, Collect, Lazy |
| Access | All, Get, Value, First, FirstWhere, FirstOrFail, Last, Sole, Before, After, Search |
| Checks | Count, Contains, ContainsStrict, DoesntContain, DoesntContainStrict, Some, Every, Has, HasAny, HasMany, HasSole, IsEmpty, IsNotEmpty, Ensure |
| Filtering | Filter, Reject, Where, WhereStrict, WhereIn, WhereInStrict, WhereNotIn, WhereNotInStrict, WhereBetween, WhereNotBetween, WhereNull, WhereNotNull, WhereInstanceOf, Only, Except |
| Mapping | Map, MapInto, MapSpread, MapWithKeys, MapToGroups, FlatMap, Pluck, Select, Transform |
| Structure | GroupBy, KeyBy, Keys, Values, Flip, Collapse, CollapseWithKeys, Flatten, Dot, Undot |
| Slicing | Take, TakeUntil, TakeWhile, Skip, SkipUntil, SkipWhile, Slice, ForPage, Nth |
| Batching | Chunk, ChunkBy, ChunkWhile, Sliding, Split, SplitIn, Partition |
| Combining | Concat, Combine, Merge, MergeRecursive, Replace, ReplaceRecursive, Union, CrossJoin, Zip, Multiply, Pad |
| Differences | Diff, DiffUsing, DiffAssoc, DiffAssocUsing, DiffKeys, DiffKeysUsing, Intersect, IntersectUsing, IntersectAssoc, IntersectAssocUsing, IntersectByKeys |
| Uniqueness | Unique, UniqueStrict, Duplicates, DuplicatesStrict |
| Ordering | Sort, SortDesc, SortBy, SortByDesc, SortKeys, SortKeysDesc, SortKeysUsing, Reverse, Shuffle, Random |
| Aggregates | Sum, Avg, Average, Min, Max, Median, Mode, CountBy, Percentage |
| Reduction | Reduce, ReduceInto, ReduceSpread |
| Flow | Each, EachSpread, Tap, Pipe, PipeInto, PipeThrough, When, Unless, WhenEmpty, WhenNotEmpty, UnlessEmpty, UnlessNotEmpty |
| Mutation | Push, Pop, Shift, Prepend, Put, GetOrPut, Pull, Forget, Splice, Transform |
| Output | Implode, Join, ToArray, ToJson, ToPrettyJson, Dump, Dd |
Take(-2) takes the last two items. Slice accepts negative offsets and lengths. Chunk retains item keys by default; pass preserveKeys: false to reset each chunk's indexes. ChunkBy groups adjacent equal values, while GroupBy gathers matching values from the whole collection. Split distributes the remainder across the first groups; SplitIn fills each group before moving to the next.
Sum returns a decimal; Avg/Average, Median, and Percentage return nullable decimals. Empty averages, medians, modes, minima, maxima, and percentages return null; an empty sum is zero. Null entries are excluded from averages and medians. Comparers passed to Sort, SortKeysUsing, and comparison-based set operations return a negative number, zero, or a positive number.
Merge appends numeric keys and replaces matching string keys. Union keeps the original value for each existing key. Replace overwrites matching keys, including numeric keys. Diff and Intersect preserve the original keys and duplicate values. For key-based set operations, pass a collection, for example settings.DiffKeys(Collect(otherSettings)).
Dd() prints and throws CollectionDumpException to stop the current operation; it never terminates the web server process.
Callbacks and Comparisons
var active = users.Filter(u => u.Active);
var adults = users.Where("Age", ">=", 18);
var emails = users.WhereNotNull("Email").Pluck("Email");
var page = users.ForPage(2, 20);
var indexed = users.Map((user, key) => new { Key = key, user.Name });
users.Each(user =>
{
if (!user.Active) return false; // stop iteration
Process(user);
return true;
});Filter() without a callback removes PHP-style false values: null, false, zero, "", "0", and empty arrays/collections. Loose comparisons match numeric strings to numbers. The Strict variants distinguish them. Strongly typed C# collections can still use loose value searches: Collect(new[] { 4 }).Contains("4") is true, while ContainsStrict("4") is false.
Where accepts =, ==, !=, <>, <, >, <=, >=, ===, !==, and <=>. A single field name tests its truthiness. Where(predicate) remains an alias for Filter(predicate).
Tap invokes a callback with the same collection and returns it. Pipe returns the callback's result. PipeThrough accepts successive Func<object?, object?> callbacks. When/Unless return the callback result, or the original collection when no callback is selected or it returns null.
Reduce accepts an explicit initial accumulator. ReduceInto supports mutable reference accumulators and a ref delegate for value types. ReduceSpread receives and returns an accumulator array:
var total = numbers.Reduce((sum, number) => sum + number, 0);
var doubled = numbers.ReduceInto(new List<int>(), (list, number) => list.Add(number * 2));
var sumAndCount = numbers.ReduceSpread(
(state, number, key) => new object?[] { (int)state[0]! + number, (int)state[1]! + 1 },
0, 0);Grouping and Plucking
GroupBy and KeyBy return keyed collections, so collection methods remain available after grouping or indexing. GroupBy callback values may be arrays to put an item in several groups. Pass an array of field names and/or selectors for nested grouping.
var grouped = users.GroupBy("Team", preserveKeys: true);
var counts = grouped.Map(group => group.Count);
var byId = users.KeyBy(u => u.Id);
var namesById = users.Pluck(u => u.Name, u => u.Id);
var nestedNames = users.Pluck("Profile.Name", "Id");
var groupedAgain = users.GroupBy(new object[] { "Team", "Role" });Duplicate keys in KeyBy, keyed Pluck, and MapWithKeys keep the last value. MapToGroups gathers the values for each key instead. MapInto<TTarget>() calls a public constructor with the value and key, or a constructor with only the value.
Upgrading from the original LINQ wrapper: a group is now a Collection<T>, rather than an IGrouping<TKey,T>. Read its key from the second Map callback argument, as in the introduction. KeyBy returns Collection<T> rather than Dictionary<TKey,T>; keyed indexing and Get remain available.
Mutating a Collection
numbers.Push(4, 5);
var last = numbers.Pop();
var firstTwo = numbers.Shift(2);
numbers.Prepend(0);
settings.Put("timezone", "UTC");
var timezone = settings.Pull("timezone"); // read and remove
settings.Forget("debug");
numbers.Transform(n => n * 2);Pop() and Shift() return one item or null; counts greater than one return a collection. Splice replaces a segment and returns the removed items. Forget preserves the remaining numeric keys. Shift, unkeyed Prepend, and Splice reset numeric indexes while preserving string keys.
Lazy collections reject mutation with NotSupportedException. Call Collect() to obtain an independent mutable collection first.
Macros and Higher Order Messages
C# extension methods remain available. Runtime macros are registered per item type and work on eager and lazy collections of that type:
Collection<string>.Macro("ToUpper", words => words.Map(word => word.ToUpperInvariant()));
dynamic words = Collect(new[] { "first", "second" });
Collection<string> upper = words.ToUpper();
// An explicitly named call also works without a dynamic receiver:
var same = Collect(new[] { "first" }).InvokeMacro("ToUpper");Macros accepting arguments use (collection, arguments) => .... HasMacro checks registration and FlushMacros removes that type's macros.
C# higher-order messages use the Higher property:
var names = users.Higher.Map.Name;
var totalVotes = users.Higher.Sum.Votes;
users.Higher.Each.MarkAsVip();The supported operations are Average, Avg, Contains, Each, Every, Filter, First, FlatMap, GroupBy, KeyBy, Map, Max, Min, Partition, Reject, SkipUntil, SkipWhile, Some, SortBy, SortByDesc, Sum, TakeUntil, TakeWhile, and Unique.
Lazy Collections
LazyCollection<T> accepts an enumerable or a factory that returns an enumerable. Factories run when enumerating, once for each enumeration. Use an iterator method for files or large generated sequences:
IEnumerable<string> ReadLines()
{
using var reader = File.OpenText("events.log");
while (reader.ReadLine() is { } line)
yield return line;
}
var lines = new LazyCollection<string>(ReadLines)
.Filter(line => line.Contains("error"))
.Map(line => line.Trim())
.Take(100);
foreach (var line in lines)
Console.WriteLine(line);Filter, Map, Take, Skip, Chunk, Sliding, Flatten, and other streaming operations do not load the whole source. Take stops without reading an extra source item. Iterator resources are disposed on completion, exceptions, and early termination. Operations such as sorting, grouping, reversing, and recursive merging necessarily buffer their input, but do so only when enumerated.
Transformations on a lazy collection return a lazy instance. Shared method signatures return Collection<TResult>, whose implementation remains lazy; Collect() explicitly materializes an eager snapshot. Eager() materializes a snapshot wrapped in a lazy collection.
As in Laravel 13, lazy Collapse() and Concat() reindex their values, while CollapseWithKeys() preserves keys. Repeated keys can occur during lazy iteration; materializing with Collect, All, ToArray, or JSON keeps the last value for each key.
Additional lazy operations:
| Method | Behavior |
|---|---|
LazyCollection.Range(from, to, step) | Generate an inclusive range. |
LazyCollection.Times(count) | Generate one-based indexes; omit the count for an unbounded sequence. |
TapEach(callback) | Run a side effect only as each item is consumed. |
Remember() | Cache items incrementally and share one source iterator across subsequent enumerations. |
TakeUntilTimeout(deadline, callback) | Stop at a DateTimeOffset deadline; the optional callback receives the last item/key, or null/null if already expired. |
Throttle(seconds) | Space consumption of items, including the time spent processing them. |
WithHeartbeat(interval, callback) | Invoke a callback at intervals while consuming items. |
Eager() | Materialize now; replay the snapshot later. |
Deadlines and heartbeats use the framework's Date clock, so Date.Freeze can test them.
using var remembered = new LazyCollection<string>(ReadLines).Remember();
var firstTen = remembered.Take(10).Collect();
var firstTwenty = remembered.Take(20).Collect(); // reads only ten additional linesRemember intentionally retains a partially consumed source iterator. Dispose the returned collection to close it early. Completion and exceptions close the iterator automatically; cached items and failures are replayed without rereading the source.
Model Collections
Model queries and pagination return the same eager collection:
Collection<Post> posts = await Post.Where(p => p.Published).Get();
Collection<User> users = await User.All();
Collection<string> emails = await User.Query().Pluck(u => u.Email);Paginator<T>.Items is also a collection. Database Cursor() and Lazy() retain their asynchronous IAsyncEnumerable<T> contract for await foreach and .NET asynchronous LINQ; synchronous LazyCollection<T> does not block on asynchronous database I/O.
Collection JSON and recursive array conversion honor model [Hidden], [Visible], and [Appends] rules, including per-instance MakeHidden/MakeVisible settings.