Skip to content

Useful C# extension methods and utilities. Sponsored by endjin.

License

Notifications You must be signed in to change notification settings

corvus-dotnet/Corvus.Extensions

Repository files navigation

Corvus.Extensions

Build Status GitHub license IMM

This provides a library of useful extensions to .NET types.

It is built for netstandard2.0.

Repository Structure

  • .github - Contains GitHub repo related files, such as issue templates and GitHub Actions workflow definitions
  • Solutions - Contains files for all of the extension methods and tests

Getting Started

Corvus.Extensions is available on NuGet. To add a reference to the package in your project, run the following command

dotnet add package Corvus.Extensions

Use the --version option to specify a version to install.

dotnet add package Corvus.Extensions --version 1.1.4

Features

Casting

The CastTo method used to be necessary to avoid boxing in certain generic conversion cases. The .NET framework can now determine when boxing is not necessary, so CastTo is no longer necessary, hence why we're not including an example for it.

An AddRange() extension for ICollection<T>

AddRange()

AddIfNotExists()

Adds a value to a key, if the key does not already exist.

AddIfNotExists()

ReplaceIfExists()

Replaces a value in a key, but only if the key already exists.

ReplaceIfExists

Merge()

The union of two dictionaries. Note that this uses AddIfNotExists() semantics, so the values in the first dictionary will be preserved.

Merge

DistinctPreserveOrder()

This emits an enumerable of the distinct items in the target, preserving their original ordering.

The built-in LINQ operator Distinct can be used to return the distinct elements from a sequence. However, the documentation makes no guarantee about preserving the original ordering of the elements.

DistinctPreserveOrder()

DistinctBy()

This allows you to provide a function to provide the value for equality comparison for each item.

DistinctBy()

Concatenate()

This gives you the ability to concatenate multiple enumerables, using the params pattern.

Concatenate()

HasMinimumCount()

This determines whether the enumerable has at least a given number of items in it.

HasMinimumCount

AllAndAtLeastOne()

This is an efficient implementation of the combination of the built-in LINQ operators Any() & All() that avoids starting the enumeration twice. It determines if the collection is non-empty, and that every element also matches some predicate.

This method is also useful because of the counterintuitive behavior of All() with empty collections, whereby items.All() returns true if items is an empty collection. items.AllAndAtLeastOne() returns false if items is an empty collection, as one of the examples below shows.

AllAndAtLeastOne

ExtractPropertyName()

This extracts a property name from a lambda expression, throwing if that expression is not a MemberExpression

ExtractPropertyName

GetMemberExpression()

This extracts a MemberExpression from a LambdaExpression, throwing if the body is not a MemberExpression.

This allows a more direct expression of the expectation that an expression has this particular form. It allows us to avoid cluttering up the code with exception throwing, which can improve readability.

GetMemberExpression

RemoveAll()

This removes all items from a list that match a predicate.

RemoveAll

  • Get as a stream in various encodings
  • Base64 encode/decode (with or without URL safety)
  • Reverse
  • To camel case

AsBase64()

Convert the provided string to a base 64 representation of its byte representation in a particular encoding.

AsBase64

Base64UrlEncode()

Convert the provided string to a base 64 representation of its byte representation in the UTF8 encoding, with a URL-safe representation.

Base64UrlEncode()

Base64UrlDecode()

Convert the provided string from a base 64 representation of its byte representation in the UTF8 encoding with a URL-safe representation.

Base64UrlDecode()

AsStream()

Provide a stream over the string in the specified encoding.

AsStream()

EscapeContentType()

Escape a content type string.

EscapeContentType()

FromBase64()

Decode a string from a base64-encoded byte array with the specified text encoding.

FromBase64()

GetGraphemeClusters()

Enumerate the grapheme clusters in a string.

This method is a wrapper around StringInfo.GetTextElementEnumerator, which returns an enumerator that iterates through the text elements of a string. GetGraphemeClusters() returns an IEnumerable<string>, meaning the functionality can be used with LINQ.

You can think of GetGraphemeClusters() as enumerating through the "logical characters" in a string.

GetGraphemeClusters()

Reverse()

Reverse the string.

Reverse()

UnescapeContentType()

Unescape a content type string.

UnescapeContentType()

ToCamelCase()

Convert a string to camel case from pascal case.

ToCamelCase()

  • Casts Task/Task<?> to Task<T> result type with or without a cast of the actual result value

CastWithConversion()

CastWithConversion()

Various ForEach extensions, including:

  • async methods
  • aggregating and delaying exceptions until the end of the traversal
  • with indexing
  • until predicates are true/false

ForEachAsync()

Execute an async action for each item in the enumerable.

ForEachAsync

ForEachAtIndex()

Execute an action for each item in the enumerable with the index of the item in the enumerable.

ForEachAtIndex()

ForEachAtIndexAsync()

Execute an async action for each item in the enumerable, in turn, with the index of the item in the enumerable.

ForEachAtIndexAsync()

ForEachFailEnd()

Execute an action for each item in the enumerable.

If any operation fails, then the enumeration is continued to the end when an Aggregate Exception is thrown containing the exceptions thrown by any failed operations.

This is useful when cleaning up Azure resources that were set up for testing purposes, for example. It makes sure that even if one step fails, the process doesn't stop, as this would mean that some potentially expensive resources aren't deleted.

ForEachFailEnd()

ForEachFailEndAsync()

Execute an async action for each item in the enumerable.

Returns a task which completes when the enumeration has completed.

If any operation fails, then the enumeration is continued to the end when an Aggregate Exception is thrown containing the exceptions thrown by any failed operations.

ForEachFailEndAsync()

ForEachUntilFalse()

Execute an action for each item in the enumerable.

Returns false if the enumeration returned early, otherwise true.

ForEachUntilFalse()

ForEachUntilFalseAsync()

Execute an async action for each item in the enumerable.

Returns a task whose result is False if the enumeration returned early, otherwise returns true.

ForEachUntilFalseAsync()

ForEachUntilTrue()

Execute an action for each item in the enumerable.

Returns true if the action terminated early, otherwise false.

ForEachUntilTrue()

ForEachUntilTrueAsync()

Execute an async action for each item in the enumerable.

Returns a task whose result is True if the action terminated early, otherwise returns False.

ForEachUntilTrueAsync()

A class that provides a single static method: TaskEx.WhenAllMany()

TaskEx.WhenAllMany()

Passes the elements of a sequence to a callback that projects each element to a Task<IEnumerable<T>> and flattens the sequences produced by the resulting tasks into one Task<IList<T>>.

ForEachUntilTrue()

Contributing

This project has adopted a code of conduct adapted from the Contributor Covenant to clarify expected behavior in our community. This code of conduct has been adopted by many other projects. For more information see the Code of Conduct FAQ or contact hello@endjin.com with any additional questions or comments.

Licenses

GitHub license

Corvus.Extensions is available under the Apache 2.0 open source license.

For any licensing questions, please email licensing@endjin.com

Project Sponsor

This project is sponsored by endjin, a UK based Microsoft Gold Partner for Cloud Platform, Data Platform, Data Analytics, DevOps, and a Power BI Partner.

For more information about our products and services, or for commercial support of this project, please contact us.

We produce two free weekly newsletters; Azure Weekly for all things about the Microsoft Azure Platform, and Power BI Weekly.

Keep up with everything that's going on at endjin via our blog, follow us on Twitter, or LinkedIn.

Our other Open Source projects can be found on GitHub

IP Maturity Matrix (IMM)

The IMM is endjin's IP quality framework.

Shared Engineering Standards

Coding Standards

Executable Specifications

Code Coverage

Benchmarks

Reference Documentation

Design & Implementation Documentation

How-to Documentation

Date of Last IP Review

Framework Version

Associated Work Items

Source Code Availability

License

Production Use

Insights

Packaging

Deployment

OpenChain