Skip to content

Latest commit

 

History

53 Commits

Folders and files

Repository files navigation

Masterly.Extensions.Core

A rich, dependency-free set of C# extension methods for strings, collections, dictionaries, objects, types, dates, numbers, tasks and exceptions.

Masterly.Extensions.Core

Nuget Nuget GitHub last commit GitHub Build CodeQL Analysis Publish to NuGet Docs

Full documentation: a7mdfre7at.github.io/Masterly.Extensions.Core

Give a Star! ⭐

If you like or are using this project please give it a star. Thanks!

Install

dotnet add package Masterly.Extensions.Core

Works on every .NET Core 3.0+ / .NET 5+ app (netstandard2.1), with an optimized build for .NET 10. No third-party dependencies.

Upgrading from 1.x? Read the changelog: 2.0 fixes many bugs and changes some behavior.

A taste

C# lets extension methods power await, foreach, deconstruction and LINQ query syntax. This library uses that to make everyday values work with them:

// ── await anything sensible ─────────────────────────────────────────────
var (user, orders) = await (GetUserAsync(id), GetOrdersAsync(id));   // concurrent, typed results
string[] pages = await urls.Select(FetchAsync);                      // a whole list of tasks
await 2.Seconds();                                                   // a delay
await stoppingToken;                                                 // until shutdown is requested
using (await _lock) { /* one caller at a time */ }                   // SemaphoreSlim itself is awaitable
List<Order> all = await GetOrdersAsync();                            // IAsyncEnumerable<T> → List<T>
int exitCode = await Process.Start("git", "pull");                   // a process → its exit code
await foreach (string line in streamReader) { }                      // a file, line by line
using (CultureInfo.GetCultureInfo("ar-JO").Use()) { }                // a temporary culture
Config config = await lazyConfig;                                    // Lazy<Task<T>>: started on first await
await foreach (long tick in 5.Seconds()) { }                         // a periodic timer; break to stop
Config c = await LoadAsync().Then(Parse).Catch<ParseException, Config>(ex => Config.Default); // promise-style

// ── foreach, deconstruction and LINQ on ranges and lists ───────────────
foreach (int i in 0..5) { }                                          // 0, 1, 2, 3, 4
foreach (int i in (0..100).Step(5)) { }                              // 0, 5, 10, ... 95
var squares = from i in 0..10 where i % 2 == 0 select i * i;         // 0, 4, 16, 36, 64
var (name, domain) = "ahmad@example.com".Split('@');                 // "ahmad", "example.com"
foreach (DateTime d in start.To(end)) { }                            // every day, both ends included
foreach (var (item, index) in items.WithIndex()) { }                 // item with its position
foreach (var (file, progress) in files.WithProgress()) { }           // + percent, elapsed and ETA for CLIs
foreach (var (status, group) in orders.GroupBy(o => o.Status)) { }   // deconstruct a grouping
var (year, month, day) = date;                                       // 2024, 5, 17
var (hours, minutes, seconds) = stopwatch.Elapsed;                   // 1h 02m 30s → 1, 2, 30
Stack<int> stack = new Stack<int> { 1, 2, 3 };                       // initializers on Stack, Queue, LinkedList
var ports = new Dictionary<string, int> { ("http", 80), ("https", 443) }; // tuple entries; { 1, otherList } spreads

// ── async work done right ───────────────────────────────────────────────
string[] bodies = await urls.SelectAsync(FetchAsync, maxConcurrency: 4);              // bounded, ordered
Order order = await Retry.ExecuteAsync(() => api.GetOrderAsync(id), 3, 200.Milliseconds()); // with backoff
var (report, elapsed) = await BuildReportAsync().Timed();                             // result + duration
byte[] download = await mirrors.Select(DownloadAsync).FirstSuccessful();              // fastest healthy mirror
decimal price = await GetPriceAsync().WithFallback(0m, 2.Seconds());                  // never hang the page
Func<Task<Config>> loadOnce = load.SingleFlight();                   // 100 concurrent callers, 1 load (no caching after)
Func<string, CancellationToken, Task<Product[]>> search = find.Latest(); // search-as-you-type: a new call cancels the old

// ── C# 14 extension members: properties, statics and operators on BCL types
if (name.IsBlank) { }                                                // a property on string
string rule = "-" * 40;                                              // an operator on string
Dictionary<string, string> settings = defaults + overrides;          // merge; the right side wins
string shortId = Guid.NewShortId();                                  // a static member on Guid
TimeSpan fortnight = TimeSpan.FromWeeks(2);                          // the factory TimeSpan lacks
DateTime moment = DateTime.FromUnixTimeSeconds(1715774400);          // like DateTimeOffset has

// ── see your data ───────────────────────────────────────────────────────
Console.WriteLine(people.ToTable());      // ┌───────┬─────┐
                                          // │ Name  │ Age │
                                          // ├───────┼─────┤
                                          // │ Ahmad │  30 │
                                          // └───────┴─────┘
Console.WriteLine(root.ToTreeString(n => n.Children, n => n.Name));
                                          // src
                                          // ├── Strings
                                          // │   └── Casing.cs
                                          // └── Tasks
logger.LogInformation("{User}", user.ToSafeJson());   // {"Name":"Ahmad","Password":"***","ApiToken":"***"}
Console.WriteLine(latencies.ToSparkline());                   // ▁▅▃█▂   (one block per value)
Console.WriteLine(hits.ToBarChart(h => h.Method, h => h.Count, 20));
                                          // GET   ████████████████████  1,240
                                          // POST  ██████▋               410
Console.WriteLine(steps.ToTimeline(s => s.Name, s => s.Start, s => s.End, 20));
                                          // restore  ████················  0ms → 1.2s
                                          // build    ····█████████·······  1.2s → 3.9s
                                          // test     ·············███████  3.9s → 6.0s
Console.WriteLine(summary.ToBox("Release 2.0"));              // ┌─ Release 2.0 ─┐ ... └───────────────┘

// ── APIs, mapping and security ──────────────────────────────────────────
Page<Order> page = db.Orders.SortBy(sort, "total", "createdAt").ToPage(pageNumber: 2, pageSize: 20);   // allow-list
Uri url = apiBase.Append("users", userId, "orders").WithQuery(new { status = "open", page = 2 });
OrderDto dto = order.MapTo<OrderDto>();               // entity → DTO without a mapping library
entity.UpdateFrom(patchRequest);                      // PATCH: nulls skipped, nested objects merged
bool genuine = body.VerifyHmacSha256(secret, Request.Headers["X-Signature"]);   // constant-time compare
int? size = query["size"].TryParse<int>();            // null instead of an exception
(booking.Start, booking.End).Overlaps((other.Start, other.End));                // ranges are tuples
Console.WriteLine(oldConfig.DiffLines(newConfig));   // - port: 80
                                                     // + port: 8080

// ── read what people type ───────────────────────────────────────────────
"1d 2h 30m".ToTimeSpan();                 // 1.02:30:00   and back: "1 day, 2 hours, 30 minutes"
"10 MB".ToByteCount();                    // 10485760
"/users/7/orders/99".ExtractWith("/users/{id}/orders/{orderId}");   // { id: "7", orderId: "99" }
commands.ClosestMatch("statsu");          // "status" (did you mean?)
"pendng".ToClosestEnum<Status>();         // Status.Pending; settings.GetClosest("tmeout") works the same way
names.OrderByNatural();                   // file1, file2, file10 — also StringComparer.Natural
order.ContentHash();                      // stable SHA-256 of the object graph: an ETag for anything
latencies.Percentile(95);                 // p95, also Median() and StandardDeviation()

// ── objects ─────────────────────────────────────────────────────────────
before.CompareProperties(after);          // [Email: "a@x.com" -> "b@x.com", Address.City: "Amman" -> "Irbid"]
Customer copy = customer.DeepClone();     // nothing shared with the original
"Hi {Name}, you owe {Balance:C}".FormatWith(user);

// ── collections ─────────────────────────────────────────────────────────
CollectionDiff<Product> diff = saved.DiffWith(incoming, p => p.Id);   // Added / Removed / Changed / Unchanged
IReadOnlyList<Project> buildOrder = projects.TopologicalSort(p => p.References);
prices.Scan((sum, p) => sum + p);                                     // running totals
readings.Window(3).Select(w => w.Average());                          // moving average
File.WriteAllText("orders.csv", orders.ToCsv());                      // RFC 4180, safe against CSV injection

// ── text and numbers for people ─────────────────────────────────────────
"getHTTPResponse".ToKebabCase();      // "get-http-response"
"Héllo, Wörld! 2024".ToSlug();        // "hello-world-2024"
"4111111111111111".Mask();            // "************1111"
"box".ToQuantity(2);                  // "2 boxes"
123.ToWords();                        // "one hundred twenty-three"
2024.ToRoman();                       // "MMXXIV"
comment.CreatedAt.ToRelativeTime(now); // "5 minutes ago"
guid.ToShortId();                     // "WVc48X0DMUKeJzajOTX69A"

Conventions

  • No using needed. Each class lives in the namespace of the type it extends (System, System.Collections.Generic, System.Linq, System.Threading.Tasks, ...). The exceptions are GetPropertyValue/SetPropertyValue and the GetAttribute<T>/HasAttribute<T> family, which are in System.Reflection, and NameValueCollection.ToQueryString, which is in System.Collections.Specialized. Without that using, nameValues.ToQueryString() still compiles but binds to the object overload and returns the collection's properties.
  • Null handling. Invalid arguments throw ArgumentNullException / ArgumentOutOfRangeException with the parameter name. String predicates such as ContainsIgnoreCase return false for a null string instead of throwing. Every signature carries nullable annotations.
  • Culture. Comparisons are ordinal and formatting is invariant unless a method takes a culture or comparison option. Removing accents (ToSlug, RemoveDiacritics) needs the platform's globalization data: with InvariantGlobalization (common in containers and Native AOT apps) accents are kept, so "Héllo, Wörld! 2024".ToSlug() returns "héllo-wörld-2024".
  • No clock. Methods that need "now" take it as a parameter, so your code stays testable.
  • C# 14 extension members. A few members are extension properties, static members and operators (text.IsBlank, Guid.NewShortId(), defaults + overrides). They compile to ordinary static methods, so the library runs on any supported runtime, but the property/static/operator syntax needs a C# 14 compiler (the .NET 10 SDK, or Visual Studio 2026). Older compilers keep every classic x.Method() extension and report a clear "feature is not available" error if they meet the new syntax (CS9260 on C# 13, CS9202 on C# 12).
  • Trimming and Native AOT. The .NET 10 build is marked trim- and AOT-compatible. The few members that rely on reflection over runtime types or on reflection-based System.Text.Json (DeepClone, ToJsonString, FromJson, ToSafeJson, ToCanonicalJson, ContentHash, CompareProperties, ApplyTo, MapTo, UpdateFrom, SortBy, WithQuery, AsDictionary, FormatWith, GetPropertyValue, ...) carry [RequiresUnreferencedCode] / [RequiresDynamicCode], so a trimmed or AOT-published app gets a warning exactly where it matters. Members that reflect over typeof(T) (ToTable, ToCsv, ToObject<T>, ...) annotate T with [DynamicallyAccessedMembers], so they keep working after trimming.
  • Name clashes. Method names avoid clashing with LINQ on .NET 8 and 10 (Chunk, DistinctBy, CountBy, Index, Enumerable.Shuffle; the random-order method here is InRandomOrder). A few names also exist in other libraries: FluentAssertions has As<T>(), and System.Interactive (Ix) has Scan, DistinctUntilChanged and IsEmpty. If a call is ambiguous, call the method statically (EnumerableExtensions.Scan(...)) or use a using alias. The same goes for the Page<T> type if your project imports its own Page<T>.

API

String Extensions

Method Example
ContainsIgnoreCase "Hello".ContainsIgnoreCase("ELL") → true
ContainsAny "a.txt".ContainsAny(StringComparison.Ordinal, ".txt", ".md") → true
Contains(params) "abc".Contains("x", "b") → true
EqualsIgnoreCase "abc".EqualsIgnoreCase("ABC") → true
StartsWith(params) / StartsWithIgnoreCase "http://x".StartsWithIgnoreCase("HTTP://", "HTTPS://") → true
EndsWith(params) / EndsWithIgnoreCase "photo.JPG".EndsWithIgnoreCase(".jpg", ".png") → true
IsBase64 "SGVsbG8=".IsBase64() → true
IsNullOrEmpty / IsNullOrWhiteSpace name.IsNullOrWhiteSpace()
EnsureStartsWith / EnsureEndsWith "path".EnsureEndsWith('/') → "path/"
Left / Right "abcdef".Left(2) → "ab"
Truncate / TruncateFromBeginning "abcdef".Truncate(3) → "abc"
TruncateWithPostfix "Hello world".TruncateWithPostfix(8) → "Hello..."
RemovePreFix / RemovePostFix "UserService".RemovePostFix("Service") → "User"
ReplaceFirst "a-b-c".ReplaceFirst("-", "+") → "a+b-c"
Between "key=[value]".Between("[", "]") → "value"
NthIndexOf "a.b.c".NthIndexOf('.', 2) → 3
NormalizeLineEndings converts \r\n, \r, \n to Environment.NewLine
Split(string) / SplitToLines "a\nb\r\nc".SplitToLines() → ["a", "b", "c"]; text.Split(", ") binds to the BCL's own string.Split(string), which gives the same result
SplitWords "getHTTPResponse_v2".SplitWords() → ["get", "HTTP", "Response", "v2"]
ToCamelCase "HTTP response" → "httpResponse"
ToPascalCase "http_response" → "HttpResponse"
ToKebabCase "HTMLParser" → "html-parser"
ToSnakeCase "ThisIsIt" → "this_is_it"
ToConstantCase "maxRetryCount" → "MAX_RETRY_COUNT"
ToTrainCase "contentType" → "Content-Type"
ToTitleCase "user_first_name" → "User First Name"
ToSentenceCase "ThisIsSampleSentence" → "This is sample sentence"
FirstCharToUpper "hello" → "Hello"
ToSlug "Héllo, Wörld! 2024".ToSlug() → "hello-world-2024" (accents kept under InvariantGlobalization, see Culture above)
RemoveDiacritics "Crème brûlée" → "Creme brulee" (unchanged under InvariantGlobalization)
Mask "4111111111111111".Mask() → "************1111"
MaskEmail "ahmad@example.com".MaskEmail() → "a****@example.com"
LevenshteinDistance "kitten".LevenshteinDistance("sitting") → 3
Similarity "color".Similarity("colour") → 0.8333333333333334 (≈ 0.83)
ToEnum<T> "Monday".ToEnum<DayOfWeek>()
ToMd5 / ToSha256 upper-case hex digests of the UTF-8 bytes
GetBytes "abc".GetBytes() (UTF-8) or GetBytes(encoding)
FromJson<T> json.FromJson<Order>() (System.Text.Json)
FormatWith "Hi {Name}, you owe {Balance:C} for {Order.Id}".FormatWith(user) — properties or dictionary keys; {{/}} for braces
Pluralize / ToQuantity "city".Pluralize() → "cities", "person".ToQuantity(3) → "3 people"
IsValidCreditCard "4111 1111 1111 1111".IsValidCreditCard() → true (length + Luhn)
FromRoman "MMXXIV".FromRoman() → 2024
FromShortId turns a ToShortId() string back into the Guid
TryParse<T> "42".TryParse<int>() → 42, "abc".TryParse<int>() → null; numbers, bool, Guid, dates, TimeSpan, enums (invariant culture)
ToTimeSpan "1d 2h 30m", "90s", "1.5 hours", "1 day, 2 hours and 30 minutes" → TimeSpan
ToByteCount "10 MB".ToByteCount() → 10485760 (1024-based; reverse of ToFileSize)
ExtractWith "/users/7".ExtractWith("/users/{id}") → { id: "7" }, or null when it doesn't fit (reverse of FormatWith)
ExtractEmails / ExtractUrls every e-mail address / URL in free text
Wrap text.Wrap(60) — word-wraps to 60 columns
ReverseText "👍🏽 héllo".ReverseText() → "olléh 👍🏽" (emoji and accents stay intact)
WordCount / ReadingTime article.ReadingTime() → TimeSpan at 200 words per minute
Compress / Decompress GZip + Base64 for large text; Decompress refuses output over 64 MB (zip-bomb guard)
Indent(count) / Indent(prefix) "a\n\nb".Indent("> ") → "> a\n\n> b" (blank lines stay empty, line endings kept)
Dedent / Dedent(count) " a\n b".Dedent() → "a\n b" (common margin removed, like Python's textwrap.dedent)
Center "Title".Center(11, '=') → "===Title===" (extra padding goes right)
NormalizeWhitespace " a \t b\r\n c ".NormalizeWhitespace() → "a b c"
Repeat "ab".Repeat(3) → "ababab"; '-'.Repeat(10) → "----------"
TrimLines "a \nb \t\n".TrimLines() → "a\nb\n"
MatchesWildcard "report-2024.csv".MatchesWildcard("report-*.csv") → true (* any run, ? one char; iterative, no regex)
CountOccurrences "banana".CountOccurrences("ana") → 1 (non-overlapping); "a,b,c".CountOccurrences(',') → 2
CommonPrefix / CommonSuffix "interstellar".CommonPrefix("internet") → "inter"; "walking".CommonSuffix("talking") → "alking"
IsAnagramOf "Dormitory".IsAnagramOf("dirty room") → true (letters/digits only, case-insensitive)
ToBase64 / FromBase64 "Hello".ToBase64() → "SGVsbG8="; "SGVsbG8=".FromBase64() → "Hello" (UTF-8 or a given Encoding)
ToStream using Stream body = json.ToStream(); (read-only MemoryStream at position 0; caller disposes)
ParseKeyValuePairs "Server=db; Database=app".ParseKeyValuePairs()["database"] → "app" (case-insensitive keys; (',', ':') overload for other separators)
ToBox "Hello\nWorld".ToBox("Greeting") → ┌─ Greeting ─┐ / │ Hello │ / │ World │ / └────────────┘ — a box-drawing frame, title optional
ToClosestEnum<T> "pendng".ToClosestEnum<Status>() → Status.Pending; matches names or [Description] text, ignores case, null if nothing is similar enough (optional minSimilarity, default 0.5)
NaturalStringComparer names.OrderBy(n => n, NaturalStringComparer.OrdinalIgnoreCase) → file1, file2, file10 (digit runs compare numerically, null first, no overflow; also an IEqualityComparer for HashSet/Distinct)
FromCompactString "1.3M".FromCompactString() → 1300000; "1,250" → 1250, "12 K" → 12000 (reverse of ToCompactString; K, M, B, T, Qa, Qi)
DiffLines oldText.DiffLines(newText) — line diff like git diff (- , + , two spaces for unchanged)
PrettyJson / MinifyJson re-format JSON; accented and non-Latin text stays readable, HTML-sensitive characters stay escaped
TruncateWords review.TruncateWords(5) → "The food was great and..."
Highlight snippet.Highlight(query, "<mark>", "</mark>") — HTML-encodes the text first, so the result is safe to render
ToHmacSha256 / VerifyHmacSha256 webhook signatures: hex (any case), Base64 or sha256= prefix; compared in constant time
FromHex / ToBase64Url / FromBase64Url "ff00".FromHex(), URL-safe Base64 without padding
IsValidEmail / IsValidUrl / IsValidIban / IsValidJson practical validators (IsValidIban checks the mod-97 checksum)

Enumerable Extensions

Method Example
WhereIf users.WhereIf(onlyActive, u => u.IsActive) — also on IQueryable (EF Core)
Partition var (adults, minors) = people.Partition(p => p.Age >= 18);
Pairwise readings.Pairwise((before, after) => after - before)
SelectAsync await urls.SelectAsync(FetchAsync, maxConcurrency: 4) — at most 4 at once, results in input order, stops on first failure
Scan new[] { 1, 2, 3 }.Scan((sum, x) => sum + x) → 1, 3, 6
Window readings.Window(3) → sliding windows of 3
DistinctUntilChanged [1, 1, 2, 2, 1] → [1, 2, 1]; or by key: events.DistinctUntilChanged(e => e.Status)
CartesianProduct sizes.CartesianProduct(colors) → every (size, color) pair
ToCsv RFC 4180 CSV with a header row; text starting with =, +, -, @ is neutralized so spreadsheets don't run it
ToTable box-drawn text table for consoles and logs; numbers right-aligned
ToMarkdownTable GitHub-style Markdown table
ToTreeString root.ToTreeString(n => n.Children, n => n.Name) — prints a tree like the tree command
GroupAdjacent [A, A, B, A] → (A: 2), (B: 1), (A: 1) — runs of consecutive equal keys
ClosestMatch commands.ClosestMatch("statsu") → "status", or null if nothing is similar enough
Median / Percentile / StandardDeviation latencies.Percentile(95) — for double, int, long and decimal sequences
ToPage orders.ToPage(2, 20) → Page<T> with Items, TotalCount, TotalPages, HasNext, HasPrevious — on IQueryable too (COUNT + OFFSET in SQL)
SortBy query.SortBy(sort, "lastName", "age", "address.city") — reads a ?sort= parameter such as "lastName desc, -age"; give an allow-list in public APIs so clients can't sort by hidden fields; only comparable properties; null-safe nested paths; runs in SQL on IQueryable
Iterate 1.Iterate(x => x * 2).Take(10) — endless sequences
DiffWith saved.DiffWith(incoming, p => p.Id) → Added, Removed, Changed, Unchanged, HasChanges
TopologicalSort projects.TopologicalSort(p => p.References); throws CyclicDependencyException with the cycle
RecursiveJoin builds a tree from a flat list: items.RecursiveJoin(x => x.Id, x => x.ParentId, (Item x, IEnumerable<Node> children) => new Node(x, children)) (the result selector needs explicit parameter types)
RecursiveSelect flattens a tree depth-first: roots.RecursiveSelect(n => n.Children)
Union(item) ids.Union(42)
IsEmpty items.IsEmpty()
Split(size) array.Split(100) → chunks of 100
MatchAny tags.MatchAny("urgent", "bug")
MatchAll same items with the same counts, any order
AllIn every item is one of the given values
ContainsAll contains every one of the given values
ToHtmlTable renders objects as an HTML-encoded <table>
WithIndex foreach (var (item, index) in items.WithIndex())
None if (errors.None()) / orders.None(o => o.IsOverdue) — the readable opposite of Any
TakeUntil / SkipUntil lines.TakeUntil(l => l.StartsWith("END")) includes the END line; lines.SkipUntil(l => l.StartsWith("BEGIN")) starts at it
Interleave new[] { 1, 3, 5 }.Interleave(new[] { 2, 4 }) → 1, 2, 3, 4, 5 — round-robin; shorter sequences drop out
FullOuterJoin stock.FullOuterJoin(orders, s => s.Sku, o => o.Sku, (s, o, sku) => new { sku, OnHand = s?.Qty ?? 0, Ordered = o?.Qty ?? 0 }) — unmatched side is default, null keys match each other
IsSorted / IsSortedBy new[] { 1, 2, 2, 5 }.IsSorted() → true; events.IsSortedBy(e => e.Timestamp); optional IComparer
Permutations new[] { 1, 2, 3 }.Permutations() → [1,2,3], [1,3,2], [2,1,3], ... (lexicographic by position, lazy)
Combinations new[] { "a", "b", "c" }.Combinations(2) → [a,b], [a,c], [b,c]
PowerSet new[] { 1, 2 }.PowerSet() → [], [1], [2], [1,2] — bitmask order, at most 30 items
Frequencies "hello".Frequencies() → { h: 1, e: 1, l: 2, o: 1 }; or by key: orders.Frequencies(o => o.Status)
Flatten new[] { new[] { 1, 2 }, new[] { 3 } }.Flatten() → 1, 2, 3 (one level)
JoinWith new[] { 1.5, 2 }.JoinWith(", ") → "1.5, 2" — invariant culture, null items become empty; ids.JoinWith(',')
MinMax var (low, high) = prices.MinMax(); — one pass; optional IComparer
InRandomOrder questions.InRandomOrder(new Random(seed)).Take(10) — Fisher–Yates on a copy, deterministic per seed
WithProgress `foreach (var (file, progress) in files.WithProgress()) Console.Write($"
{progress}");→"3/10 (20%), 1.2s elapsed, ~4.8s left"; also Percent, Fraction, EstimatedRemaining, IsLast`
ToSparkline new[] { 1, 5, 3, 8, 2 }.ToSparkline() → "▁▅▃█▂" — one block per value, scaled between min and max; for double, int, long and decimal sequences; NaN draws a space
ToBarChart hits.ToBarChart(h => h.Method, h => h.Count, 20) or pairs.ToBarChart(20) → GET ████████████████████ 1,240 / POST ██████▋ 410 — bars in eighths of a cell, values invariant
ToHistogram new[] { 1, 2, 2, 3, 8, 9 }.ToHistogram(2, 10) → 1 – 5 ██████████ 4 / 5 – 9 █████ 2 — equal-width buckets, max in the last one; for double, int and long
ToTimeline steps.ToTimeline(s => s.Name, s => s.Start, s => s.End, 20) → build ····█████████······· 1.2s → 3.9s — a text Gantt chart from DateTime or TimeSpan (Stopwatch) offsets, times shown as compact offsets from the earliest start
ToColumns names.ToColumns(80) — lays strings out in columns like ls (filled top to bottom, as many columns as fit, no trailing spaces)
OrderByNatural / OrderByNaturalDescending new[] { "img12.png", "img2.png", "IMG1.png" }.OrderByNatural() → IMG1.png, img2.png, img12.png; by key: files.OrderByNatural(f => f.Name) (case-insensitive)
WithoutOutliers new[] { 10.0, 12, 11, 13, 12, 95 }.WithoutOutliers() → 10, 12, 11, 13, 12 (Tukey's fences, 1.5·IQR; double, int, long; fewer than 4 values unchanged)
Mode new[] { 3, 1, 3, 2, 1, 3 }.Mode() → 3; "mississippi".Mode() → 's' (ties: first to reach the count)
LinearTrend new[] { 2.0, 4, 6, 8 }.LinearTrend() → (Slope: 2, Intercept: 2); or points.LinearTrend() on (double X, double Y) tuples

Collection & List Extensions

Method Example
IsNullOrEmpty list.IsNullOrEmpty()
AddIfNotContains roles.AddIfNotContains("admin")
RemoveAll(predicate) / RemoveAll(items) IList<CartItem> removed = cart.RemoveAll(i => i.Quantity == 0) on any ICollection<T> — returns the removed items (on a List<T> variable the BCL's own RemoveAll wins and returns the count)
InsertRange list.InsertRange(index, items) on any IList<T>
FindIndex list.FindIndex(x => x.Id == id) on any IList<T> (List<T> has its own instance FindIndex)
AddFirst / AddLast list.AddFirst(item)
InsertBefore / InsertAfter steps.InsertAfter(s => s.Name == "Build", testStep)
ReplaceOne / ReplaceWhile list.ReplaceWhile(x => x.IsStale, x => x.Refresh())
MoveItem list.MoveItem(x => x.Id == id, 0) → true if found
GetOrAdd list.GetOrAdd(x => x.Key == key, () => new Item(key))
Deconstruction var (first, second) = list; — 2 to 5 items, works on arrays (text.Split(',')); extra items are ignored
Collection initializers new Stack<int> { 1, 2, 3 } (3 on top), new Queue<T> { .. }, new LinkedList<string> { "a", "b" }, new ConcurrentQueue<int> { 1, 2 }, new ConcurrentStack<int> { .. }
Tuple entries new Dictionary<string, int> { ("http", 80), ("https", 443) } — duplicates throw like Add
Spread in initializers new List<int> { 1, existingIds, 99 } appends every item of existingIds (instance Add(T) still wins when the element is a T)
Grouping deconstruction foreach (var (status, group) in orders.GroupBy(o => o.Status))

Dictionary Extensions

Method Example
GetOrDefault settings.GetOrDefault("theme")
GetOrAdd cache.GetOrAdd(key, k => Load(k)) or cache.GetOrAdd(key, () => Load(key)) on any IDictionary; on a ConcurrentDictionary the library adds the thread-safe () => Load(key) form (k => ... is the BCL's own GetOrAdd)
TryGetValue<T> values.TryGetValue("count", out int count)
ToObject<T> new Dictionary<string, object?> { ["Age"] = "42" }.ToObject<Person>()
ToQueryString parameters.ToQueryString() → q=a%26b&page=2
Merge defaults.Merge(overrides) (overrides win), or a.Merge(b, (key, x, y) => x + y)
Invert { "JO": "Jordan" } → { "Jordan": "JO" }
NameValueCollection.ToQueryString repeats keys with several values
GetOrDefault(key, default) settings.GetOrDefault("theme", "light") — on Dictionary, IDictionary, IReadOnlyDictionary, ConcurrentDictionary
Increment hits.Increment(url) → new count (missing key starts at 0); totals.Increment(sku, quantity) — int counters only
RemoveWhere cache.RemoveWhere((key, entry) => entry.ExpiresAt < now) → number removed
AddOrUpdate lastSeen.AddOrUpdate(userId, now, (id, previous) => previous > now ? previous : now) — ConcurrentDictionary semantics for plain dictionaries
GetClosestKey settings.GetClosestKey("tmeout") → "timeout" (did you mean?) — exact key wins without scoring; on Dictionary, IDictionary, IReadOnlyDictionary or any pairs
GetClosest settings.GetClosest("tmeout") → the value under "timeout", or default if nothing is close enough (optional minSimilarity)

Object Extensions

Method Example
Is<T> / Is(type) shape.Is<Circle>()
As<T> obj.As<Order>()
To<T> / To(type) "42".To<int>(), "1".To<DayOfWeek>(), "01:30:00".To<TimeSpan>()
IsIn status.IsIn(Status.Active, Status.Pending)
If query.If(sortByName, q => q.OrderBy(x => x.Name))
AsDictionary property names → values
ToQueryString new { Page = 2, Ids = new[] { 1, 2 } }.ToQueryString() → Page=2&Ids=1&Ids=2
TrimStringProperties trims every writable string property in place
IsNumber value.IsNumber()
ToJsonString order.ToJsonString() (System.Text.Json)
GetPropertyValue / SetPropertyValue using System.Reflection; — read or write a property by name
CompareProperties before.CompareProperties(after) → [Email: "a@x.com" -> "b@x.com", Address.City: ...] — an audit log in one line
DeepClone order.DeepClone() — full copy via System.Text.Json (records, fields, private setters, get-only collections; cycles throw)
MapTo<T> order.MapTo<OrderDto>() — same-name properties, type conversion, nested objects, lists, arrays and sets; graphs with back-references keep their shape; fills records' init properties; never writes private setters
UpdateFrom customer.UpdateFrom(patchRequest) — PATCH: null values skipped, nested objects updated in place; give the DTO nullable properties (bool?) and only the fields a client may change
ToSafeJson JSON for logs with secrets masked (Password, ApiToken, cvv, ConnectionString, ...): user.ToSafeJson("Salary")
Pipe / Tap input.Pipe(Parse).Tap(Log).Pipe(Score) — read calls left to right
ToCanonicalJson new { Zip = "11183", City = "Amman" }.ToCanonicalJson() → {"City":"Amman","Zip":"11183"} — property names sorted ordinally at every depth, no whitespace; arrays keep order
ContentHash order.ContentHash() → 64 lower-case hex chars (SHA-256 of the canonical JSON) — a stable ETag / change detector regardless of property order, runtime type or dictionary implementation
ApplyTo before.CompareProperties(after).ApplyTo(entity) — replays changes along dotted paths (Address.City), converting to the property type; unknown, read-only or null-parent paths throw ArgumentException naming the path

Function Extensions

C# cannot call a method directly on a lambda or method name, so assign it to a delegate first: Func<string, Config> load = LoadConfig;

Method Example
Memoize Func<string, Config> cached = load.Memoize(); — computes each argument once (1 or 2 arguments, thread-safe)
MemoizeAsync Func<string, Task<Config>> load = LoadAsync; var cached = load.MemoizeAsync(5.Minutes()); — shared in-flight calls, failures not cached, time-to-live counted from completion, expired entries swept
Debounce Action save = SaveDraft; Action onKeystroke = save.Debounce(500.Milliseconds()); — runs once after calls stop
Throttle Action refresh = Refresh; Action onScroll = refresh.Throttle(1.Seconds()); — at most once per second, last call never lost
Once Action init = Initialize; Action ensureInit = init.Once(); — runs once, thread-safe; Func<T> variant caches the result (a throwing run retries)
Negate items.Where(isValid.Negate()) — the opposite predicate
Compose Func<string, Config> load = parse.Compose(validate); — parse first, then validate
SingleFlight Func<Task<Config>> loadOnce = load.SingleFlight(); — calls that overlap share one run and one task; nothing is cached after it completes (Go's singleflight, the thundering-herd fix). Keyed: Func<int, Task<User>> fetchOnce = fetch.SingleFlight(); de-duplicates per key
Latest Func<string, CancellationToken, Task<Product[]>> searchLatest = search.Latest(); — every call cancels the token of the previous in-flight call (linked with the caller's own token); superseded calls see OperationCanceledException. Also Func<CancellationToken, Task<T>>

IO, Process & Culture Extensions

Method Example
foreach / await foreach over a TextReader await foreach (string line in File.OpenText(path)) { ... } — lazy, line by line
await process int exitCode = await Process.Start("dotnet", "build");
WaitForExitCodeAsync await process.WaitForExitCodeAsync(cancellationToken)
ReadAllTextAsync / ToByteArrayAsync string body = await Request.Body.ReadAllTextAsync(); — the stream stays open
Append / WithQuery apiBase.Append("users", id).WithQuery(new { page = 2 }) — every segment and value is encoded; null, empty, . and .. segments throw, as do values with no meaningful text form (anonymous objects, key/value pairs); collections expand into several segments; Append() with no segments returns the URL unchanged; WithQuery takes an object, a dictionary or key/value pairs and replaces parameters with the same name
Use using (CultureInfo.GetCultureInfo("ar-JO").Use()) { ... } — switches culture and UI culture, restores on dispose

Type & Enum Extensions

Method Example
IsAssignableTo<T> / IsAssignableTo(type) type.IsAssignableTo<IDisposable>(); on .NET 5+ type.IsAssignableTo(other) binds to the BCL's own Type.IsAssignableTo, which gives the same result
IsAssignableToGenericType typeof(List<int>).IsAssignableToGenericType(typeof(IEnumerable<>)) → true
GetInterfacesAndAbstractClasses interfaces plus abstract base classes
GetFullNameWithAssemblyName "MyApp.Order, MyApp"
IsComplex false for primitives, enums, string, decimal, dates, Guid, Uri
GetDescription reads [Description("...")], falls back to the name
GetFlags (Read | Write).GetFlags() → [Read, Write]
ToShortId guid.ToShortId() → 22-character URL-safe id instead of 36 characters
GetAttribute<T> / GetAttribute<T>(inherit) (any MemberInfo) typeof(Order).GetProperty("Total")!.GetAttribute<RangeAttribute>()?.Minimum
GetAttributes<T> typeof(Controller).GetAttributes<AuthorizeAttribute>() → every [Authorize], inherited ones included
HasAttribute<T> typeof(LegacyService).HasAttribute<ObsoleteAttribute>() → true
GetAttribute<T> (enum member) Status.Pending.GetAttribute<DescriptionAttribute>()?.Description → "Waiting for payment"; undefined values → null
IsDefined ((DayOfWeek)9).IsDefined() → false; (FileAccess.Read | FileAccess.Write).IsDefined() → true
WithFlag / WithoutFlag FileAccess.Read.WithFlag(FileAccess.Write) → ReadWrite; ReadWrite.WithoutFlag(Write) → Read
HasAnyFlag FileAccess.Read.HasAnyFlag(FileAccess.ReadWrite) → true (HasFlag needs all bits)
IsNullableValueType / UnwrapNullable typeof(int?).IsNullableValueType() → true; typeof(int?).UnwrapNullable() → typeof(int)
GetDefaultValue typeof(int).GetDefaultValue() → 0; typeof(string).GetDefaultValue() → null
IsAnonymous new { Id = 1 }.GetType().IsAnonymous() → true
IsRecord typeof(Point).IsRecord() → true for record Point(int X, int Y) and record structs
IsStatic typeof(Math).IsStatic() → true
GetGenericArgumentsOf typeof(List<int>).GetGenericArgumentsOf(typeof(IEnumerable<>)) → [typeof(int)]; null when unrelated
IsNumeric typeof(decimal?).IsNumeric() → true; typeof(DayOfWeek).IsNumeric() → false
GetFriendlyName typeof(Dictionary<string, List<int>>).GetFriendlyName() → "Dictionary<string, List<int>>"
ToHex / ToBase64Url (byte[]) hash.ToHex() → lower-case hex

Date & Time Extensions

Method Example
Milliseconds … Weeks 5.Minutes(), 1.5.Hours(), 2.Weeks()
Before / After 2.Hours().Before(now)
StartOfDay / EndOfDay date.EndOfDay() → 23:59:59.9999999
StartOfWeek / EndOfWeek date.StartOfWeek() (Monday), date.StartOfWeek(DayOfWeek.Sunday)
StartOfMonth / EndOfMonth / StartOfYear / EndOfYear date.EndOfMonth()
IsWeekend date.IsWeekend()
AddBusinessDays Friday .AddBusinessDays(1) → Monday
Age birthDate.Age(today)
ToRelativeTime "just now", "5 minutes ago", "yesterday", "in 3 days"
To foreach (DateTime day in start.Date.To(end.Date)), or with a step: start.To(end, 30.Minutes())
Quarter / WeekOfYear date.Quarter() → 1–4; date.WeekOfYear() → ISO 8601 week
Next / Previous today.Next(DayOfWeek.Friday) — always strictly after/before
ToHumanString span.ToHumanString() → "1 day, 2 hours, 30 minutes"; ToHumanString(2) keeps the 2 largest units
RoundTo / FloorTo / CeilingTo time.RoundTo(15.Minutes()) → 10:07 → 10:00, 10:08 → 10:15; elapsed.RoundTo(1.Seconds()) (DateTime keeps its Kind; TimeSpan rounds half away from zero)
StartOfQuarter / EndOfQuarter date.StartOfQuarter() → April 1st for a May date
IsSameDay / IsSameMonth / IsSameWeek a.IsSameDay(b), a.IsSameWeek(b, DayOfWeek.Sunday)
BusinessDaysUntil Friday .BusinessDaysUntil(Monday) → 1; the inverse of AddBusinessDays
ToUnixTimeSeconds / ToUnixTimeMilliseconds utcNow.ToUnixTimeSeconds() → 1715774400 (Unspecified is treated as UTC)
FromUnixTimeSeconds / FromUnixTimeMilliseconds 1715774400L.FromUnixTimeSeconds() → 2024-05-15 12:00 UTC
NthWeekdayOfMonth / LastWeekdayOfMonth date.NthWeekdayOfMonth(DayOfWeek.Tuesday, 2) → the 2nd Tuesday (null if there is no 5th); date.LastWeekdayOfMonth(DayOfWeek.Friday)
Date deconstruction var (year, month, day) = date; or var (y, m, d, hour, minute, second) = moment;
Duration deconstruction var (hours, minutes, seconds) = elapsed; (days folded into hours) or var (days, hours, minutes, seconds) = elapsed;

Number & Comparable Extensions

Method Example
ToOrdinal 21.ToOrdinal() → "21st"
ToFileSize bytes.Length.ToFileSize() → "3.3 MB" (int and long)
ToWords 1_000_001.ToWords() → "one million one"
ToCompactString 1_250_000.ToCompactString() → "1.3M"
ToRoman 1994.ToRoman() → "MCMXCIV"
IsBetween age.IsBetween(18, 65)
Clamp 150.Clamp(0, 100) → 100
RoundTo 19.97m.RoundTo(0.05m) → 19.95, 17.RoundTo(6) → 18 (decimal, double, int, long)
Overlaps / Includes (start, end).Overlaps((otherStart, otherEnd)), (9, 17).Includes(hour) — half-open ranges on tuples
Range foreach foreach (int i in 0..10) (end is exclusive)
Step (0..100).Step(5), or counting down: (10..0).Step(-3) → 10, 7, 4, 1
LINQ on ranges from i in 0..10 where i % 2 == 0 select i * i, from x in 0..3 from y in 0..3 select (x, y)
AsEnumerable (1..6).AsEnumerable().Sum() → any LINQ method
IsEven / IsOdd count.IsEven() (int and long)
PercentOf 25.PercentOf(200) → 12.5 (int, decimal, double; total == 0 throws)
ToOrdinalWords 21.ToOrdinalWords() → "twenty-first", 100 → "one hundredth"
Digits / DigitSum 1234.Digits() → [1, 2, 3, 4], 1234.DigitSum() → 10 (int and long, sign ignored)
Rescale 0.5.Rescale(0, 1, 0, 100) → 50; celsius.Rescale(0, 100, 32, 212) → Fahrenheit
ToFraction 0.75.ToFraction() → "3/4", 1.75 → "1 3/4", 3.14159 → "3 16/113", 3.14159.ToFraction(10) → "3 1/7" (double and decimal; closest fraction with denominator ≤ 1000 by default)

Random Extensions

Every method is deterministic for a seeded Random and none is cryptographic — they are for test data, samples and games.

Method Example
NextItem random.NextItem(names) or random.NextItem("red", "green", "blue")
NextItems random.NextItems(deck, 5) → 5 distinct cards (no replacement)
NextBool random.NextBool() fair coin; random.NextBool(0.1) → true one time in ten
NextDouble / NextDecimal random.NextDouble(-1.0, 1.0); random.NextDecimal(0m, 100m) → [min, max)
NextString random.NextString(8) → "k3Jd0qXa"; random.NextString(6, "0123456789") → "502913"
NextEnum random.NextEnum<DayOfWeek>() → a declared member
NextDateTime / NextTimeSpan random.NextDateTime(start, end) (tick precision, keeps Kind); random.NextTimeSpan(TimeSpan.Zero, 1.Hours())
NextGaussian random.NextGaussian() (mean 0, sd 1); random.NextGaussian(170, 10)
Shuffle random.Shuffle(list) in-place Fisher–Yates on any IList<T>
NextGuid new Random(42).NextGuid() → same v4-shaped GUID every run (test data, not cryptographic)

Task Extensions

Method Example
await (t1, t2, ...) var (a, b) = await (GetAAsync(), GetBAsync()); — 2 to 5 tasks
await tasks int[] sizes = await files.Select(GetSizeAsync); — any sequence of tasks
await timeSpan await 500.Milliseconds();
await waitHandle await readyEvent; — ManualResetEvent, AutoResetEvent or Semaphore, without blocking a thread (a Mutex is rejected: use SemaphoreSlim.LockAsync)
WhenAllSettled await uploads.WhenAllSettled() → one TaskOutcome<T> per task (value or error), never throws
await cancellationToken await stoppingToken; — completes (without throwing) when cancellation is requested
LockAsync / Lock using (await _semaphore.LockAsync()) { ... }
Retry.ExecuteAsync await Retry.ExecuteAsync(() => SendAsync(), maxAttempts: 3, initialDelay: 200.Milliseconds()) — exponential backoff, optional shouldRetry filter
WithTimeout await SendAsync().WithTimeout(5.Seconds()); → TimeoutException if slow
Timed var (result, elapsed) = await QueryAsync().Timed();
FirstSuccessful await mirrors.Select(DownloadAsync).FirstSuccessful() — first success wins; AggregateException if all fail
WithFallback await GetPriceAsync().WithFallback(0m, 2.Seconds(), ex => logger.LogWarning(ex, "Slow"))
Forget SendTelemetryAsync().Forget(ex => logger.LogError(ex, "Telemetry failed"));
await lazyTask Lazy<Task<Config>> config = new(LoadConfigAsync); Config value = await config; — started by the first await, shared by every later one
await foreach over a TimeSpan await foreach (long tick in 5.Seconds()) { await PollAsync(); } — 1, 2, 3, ... every 5 s; break to stop
Every await foreach (long tick in 30.Seconds().Every(stoppingToken)) { ... } — same ticks, ends quietly on cancellation; no drift on .NET 6+
Then Config config = await LoadAsync().Then(Parse); — runs when the task succeeds; async steps flatten (Then(user => GetOrdersAsync(user)) is a Task<Order[]>)
Catch int count = await CountAsync().Catch<TimeoutException, int>(ex => -1); — exception type first, then result; on a plain Task: task.Catch<HttpRequestException>(ex => Log(ex))
InCompletionOrder foreach (Task<Page> next in urls.Select(FetchAsync).InCompletionOrder()) { Page page = await next; } — fastest first
await semaphore using (await _lock) { ... } — same release-once handle as LockAsync()
await asyncEnumerable List<Order> all = await GetOrdersAsync(); — materializes an IAsyncEnumerable<T>; for cancellation use await foreach (... in stream.WithCancellation(token))

Exception Extensions

Method Example
GetAllMessages "Could not save order --> Connection refused"
FindInnerException<T> ex.FindInnerException<SqlException>()
GetRootCause ex.GetRootCause() → the innermost exception (follows the first branch of an AggregateException)
GetAllExceptions ex.GetAllExceptions() → the exception and every inner one, outermost first, every AggregateException branch
Rethrow failure.Rethrow(); — throws a stored exception with its original stack trace ([DoesNotReturn])

C# 14 Extension Members

Member Example
string.IsBlank (property) if (name.IsBlank) — null, empty or white space
string * int (operator) "-" * 40 → a 40-character rule; "ab" * 3 → "ababab"
Guid.IsEmpty (property) if (order.Id.IsEmpty)
Guid.NewShortId() (static) string id = Guid.NewShortId(); → 22-character URL-safe id
TimeSpan.FromWeeks (static) TimeSpan.FromWeeks(2) → 14 days
DateTime.FromUnixTimeSeconds / FromUnixTimeMilliseconds (static) DateTime.FromUnixTimeSeconds(1715774400) → UTC DateTime
IReadOnlyDictionary + IReadOnlyDictionary (operator) Dictionary<string, string> settings = defaults + overrides; — same as Merge, the right side wins
StringComparer.Natural / NaturalIgnoreCase (static) names.OrderBy(n => n, StringComparer.Natural) — the natural-order comparers, where the built-in ones live

Disposable Extensions

Method Example
AsDisposable Action restore = () => Console.Title = old; using (restore.AsDisposable()) { ... } — runs the action once on dispose, thread-safe
DisposeAll new IDisposable?[] { reader, transaction, connection }.DisposeAll(); — disposes every item even if one throws; one failure is rethrown, several become an AggregateException

Building from source

dotnet restore
dotnet build --configuration Release --no-restore
dotnet test --no-restore            # needs the .NET 8 and .NET 10 runtimes

The build treats warnings as errors and enforces the code style in .editorconfig.

Benchmarks

dotnet run -c Release --project benchmarks/Masterly.Extensions.Core.Benchmarks            # everything
dotnet run -c Release --project benchmarks/Masterly.Extensions.Core.Benchmarks -- --filter *StringBenchmarks*

BenchmarkDotNet suites cover the hot-path string helpers (SplitWords, ToKebabCase, ToSlug, LevenshteinDistance, FormatWith), the sequence and graph helpers (Window, Scan, Percentile, TopologicalSort, DiffWith, ToCsv) and the reflection/JSON-based object helpers (CompareProperties, DeepClone, ToSafeJson, ToQueryString).

License

MIT Free Software, Hell Yeah!

Releases

Packages

Used by

Contributors

Languages