General-purpose utility and extension methods
Returns true
if all elements in a collection are are unique.
Usage:
bool yes = new[] { 1, 2, 3, 4, 5 }.AreUnique();
// -> true
var people = new[]
{
new Person("John", "Doe"),
new Person("Jane", "Doe"),
new Person("Jon", "Snow")
};
var no = people.AreUniqueBy(p => p.LastName);
// -> false
Returns a shuffled copy of the collection, using a cryptographically secure random number generator (just because).
Usage:
IEnumerable<int> shuffled = new[] { 1, 2, 3, 4, 5 }.CryptoShuffle();
// -> [3, 1, 4, 2, 5]
// (or some other randomized order)
Returns the left and right collections, minus overlapping values.
Usage:
var left = new[] { 1, 2, 3 };
var right = new[] { 3, 4, 5 };
var (leftOnly, rightOnly) = left.Disjunction(right);
// leftOnly = [1, 2]
// rightOnly = [4, 5]
Returns a the left collection concatenated by the right collection, minus overlapping values.
Usage:
var left = new[] { 1, 2, 3 };
var right = new[] { 3, 4, 5 };
var everythingButIntersection = left.DisjunctiveUnion(right);
// -> [1, 2, 4, 5]
Flattens a nested collection. Synonymous with nestedCollection.SelectMany(list => list)
.
Usage:
int[][] matrix = new[]
{
new[] { 1, 2, 3 },
new[] { 4, 5, 6 },
new[] { 7, 8, 9 },
};
int[] array = matrix.Flatten();
// -> [1, 2, 3, 4, 5, 6, 7, 8, 9]
Like List<T>.ForEach
, but usable on any IEnumerable
Usage:
var countries = new[] { "Canada", "United States", "Mexico" };
countries.ForEach(Console.WriteLine);
Merges 2 dictionaries, with the left dictionary winning on key conflicts.
Usage:
var person = new Dictionary<string, string>
{
{ "First Name", "John" },
{ "Last Name", "Doe" },
};
var employee = new Dictionary<string, string>
{
{ "First Name", "Chris" },
{ "Last Name", "Cringle" },
{ "Occupation", "Delivery man" },
};
var merged = person.Merge(employee);
/*
{
"First Name": "John",
"Last Name": "Doe",
"Occupation": "Delivery man"
}
*/
Merges 2 dictionaries, with the right dictionary winning on key conflicts.
Separates the collection into 2 collections: 1 with elements where the predicate is true, and the other where it's false.
Usage:
int IsEven(number) => number % 2 == 0;
var numbers = new[] { 1, 2, 3, 4, 5 };
var (evens, odds) = numbers.SeparateBy(IsEven);
// evens = [2, 4]
// odds = [1, 3, 5]
Copies and shuffles the collection.
Optionally accepts a custom Random
object, or a Func<int, int>
random number generator.
If given a custom callback, provides the number of elements in the array.
Usage:
var cards = new[] { 1, 2, 3, 4, 5 };
var shuffled = cards.Shuffle();
// [3, 2, 4, 5, 1]
// (or some other randomized order)
Usage (custom shuffler):
using RNG = System.Security.Cryptography.RandomNumberGenerator;
var cards = new[] { 1, 2, 3, 4, 5 };
// synonymous with `cards.CryptoShuffle()`
var wellShuffled = cards.Shuffle(count => RNG.GetInt32(count));
Swaps the elements at 2 indices. This mutates the original list!
Usage:
var letters = new[] { "a", "b", "c", "d" };
letters.Swap(0, 3);
// -> ["d", "b", "c", "a"]