A curated collection of useful C# snippets that you can understand in 30 seconds or less.
Note: This project is inspired by 30 Seconds of Code, but there is no affiliation with that project.
View contents
View contents
allEqual
any
arrayToCsv
bifurcate
bubbleSort
chunk
compact
countBy
countOccurences
deepFlatten
difference
differenceBy
differenceWith
drop
dropRight
dropRightWhile
dropWhile
everyNth
filterNonUnique
filterNonUniqueBy
findLast
findLastIndex
flatten
forEachRight
groupBy
hasDuplicates
head
indexOfAll
initial
initialize2DArray
initializeArrayWithRange
initializeArrayWithRangeRight
initializeArrayWithValues
initializeNDArray
intersection
intersectionBy
intersectionWith
isSorted
join
jsonToCsv
last
longestItem
maxN
minN
none
nthElement
offset
orderBy
partition
permutations
pluck
pull
pullAtIndex
pullAtValue
pullBy
reduceFilter
reduceSuccessive
reduceWhich
reject
remove
sample
sampleSize
shank
shuffle
similarity
sortedIndex
sortedIndexBy
sortedLastIndex
sortedLastIndexBy
stableSort
symmetricDifference
symmetricDifferenceBy
symmetricDifferenceWith
tail
take
takeRight
takeRightWhile
takeWhile
toHash
union
unionBy
unionWith
uniqueElements
uniqueElementsBy
uniqueElementsByRight
uniqueSymmetricDifference
without
xProd
View contents
approximatelyEqual
average
averageBy
binomialCoefficient
degreesToRads
digitize
distance
factorial
fibonacci
gcd
geometricProgression
inRange
isDivisible
isEven
isPrime
isOdd
lcm
luhnCheck
max
median
min
primes
radsToDegrees
randomIntArrayInRange
randomIntegerInRange
randomNumberInRange
round
sdbm
standardDeviation
sum
sumBy
View contents
byteSize
capitalize
capitalizeEveryWord
countVowels
csvToArray
csvToJson
decapitalize
endsWithRegex
escapeHtml
escapeRegExp
fromCamelCase
indentString
isAbsoluteUrl
isAnagram
isLowerCase
isUpperCase
mask
pad
palindrome
pluralize
removeNonAscii
reverseString
sortCharactersInString
splitLines
startsWithRegex
stringPermutations
stripHtmlTags
toCamelCase
toKebabCase
toSnakeCase
toTitleCase
truncateString
unescapeHTML
urlJoin
words
View contents
View contents
Returns the day of the current year
Already integrated into C# https://docs.microsoft.com/de-de/dotnet/api/system.datetime.dayofyear?view=netframework-4.7.2
using System;
namespace conplement.snippets.Date
{
public static partial class Date
{
public static int DayOfYear()
{
return DateTime.Now.DayOfYear;
}
}
}
Examples
conplement.snippets.Date.DayOfYear() # 12/31/2016: day 366 of 2016 (Leap Year)
Returns the human readable format of the given number of milliseconds.
// TODO
Examples
// TODO
Returns a string of the form HH:MM:SS
from a DateTime
or TimeSpan
object.
// TODO
Examples
// TODO
Returns the difference (in days) between two dates.
// TODO
Examples
// TODO
Converts an integer to a suffixed string, adding am
or pm
based on its value.
// TODO
Examples
// TODO
Check if a date is after another date.
// TODO
Examples
// TODO
Check if a date is before another date.
// TODO
Examples
// TODO
Check if a date is the same as another date.
// TODO
Examples
// TODO
Returns the maximum of the given dates.
// TODO
Examples
// TODO
Returns the minimum of the given dates.
// TODO
Examples
// TODO
Returns tomorrow's date.
// TODO
Examples
// TODO
Check if all elements in an array are equal.
// TODO
Examples
// TODO
Returns true
if the provided predicate function returns true
for at least one element in a collection, false
otherwise.
// TODO
Examples
// TODO
Converts a 2D array to a comma-separated values (CSV) string.
// TODO
Examples
// TODO
Splits values into two groups. If an element in filter
is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
// TODO
Examples
// TODO
bubbleSort uses the technique of comparing and swapping
// TODO
Examples
// TODO
Chunks an array into smaller arrays of a specified size.
// TODO
Examples
// TODO
Removes invalid values from an array.
// TODO
Examples
// TODO
Groups the elements of an array based on the given function and returns the count of elements in each group.
// TODO
Examples
// TODO
Counts the occurrences of a value in an array.
// TODO
Examples
// TODO
Deep flattens an array of arrays.
// TODO
Examples
// TODO
Returns the difference between two arrays.
// TODO
Examples
// TODO
Returns the difference between two arrays, after applying the provided function to each array element of both.
// TODO
Examples
// TODO
Filters out all values from an array for which the comparator function does not return true
.
// TODO
Examples
// TODO
Returns a new array with n
elements removed from the left.
// TODO
Examples
// TODO
Returns a new array with n
elements removed from the right.
// TODO
Examples
// TODO
Removes elements from the end of an array until the passed function returns true
. Returns the remaining elements in the array.
// TODO
Examples
// TODO
Removes elements in an array until the passed function returns true
. Returns the remaining elements in the array.
namespace conplement.snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<T> DropWhile<T>(this IEnumerable<T> list, Func<T, bool> filter)
{
if (list == null)
{
throw new ArgumentNullException(nameof(list));
}
if (filter == null)
{
throw new ArgumentNullException(nameof(filter));
}
var reachedDropPoint = false;
foreach (var element in list)
{
if (!reachedDropPoint && !filter(element))
{
continue;
}
reachedDropPoint = true;
yield return element;
}
yield break;
}
}
}
Examples
new List<int>{ 1, 2, 3, 4, 1}.DropWhile(x => x => x > 2); # new List<int> { 3, 4, 1 }
Returns every nth element in an array.
// TODO
Examples
// TODO
Filters out the non-unique values in an array.
// TODO
Examples
// TODO
Filters out the non-unique values in an array, based on a provided comparator function.
// TODO
Examples
// TODO
Returns the last element for which the provided function returns a truthy value.
// TODO
Examples
// TODO
Returns the index of the last element for which the provided function returns a truthy value.
// TODO
Examples
// TODO
Flattens an array up to the specified depth.
// TODO
Examples
// TODO
Executes a provided function once for each array element, starting from the array's last element.
// TODO
Examples
// TODO
Groups the elements of an array based on the given function.
// TODO
Examples
// TODO
Checks an array for duplicate values. Returns true if duplicate values exist and false if values are all unique.
// TODO
Examples
// TODO
Returns the head of a list.
// TODO
Examples
// TODO
Returns all indices of a value
in an array.
If the value
never occurs, returns []
.
// TODO
Examples
// TODO
Returns all the elements of an array except the last one.
// TODO
Examples
// TODO
Initializes a 2D array of given width and height and value.
namespace conplement.snippets.Enumerable
{
public static partial class Enumerable
{
public static T[,] Initialize2DArray<T>(uint width, uint height, T defaultValue = default(T))
{
if (width == 0)
{
throw new ArgumentException($"Minimum {nameof(width)} has to be 1", nameof(width));
}
if (height == 0)
{
throw new ArgumentException($"Minimum {nameof(height)} has to be 1", nameof(height));
}
var newArray = new T[width, height];
for (int widthIndex = 0; widthIndex < width; widthIndex++)
{
for (int heightIndex = 0; heightIndex < height; heightIndex++)
{
newArray[widthIndex, heightIndex] = defaultValue;
}
}
return newArray;
}
}
}
Examples
Enumerable.Initialize2DArray(2, 2, 0) # new int[2, 2] { { 0, 0 }, { 0, 0 } }
Initializes an array containing the numbers in the specified range where start
and end
are inclusive with their common difference step
.
// TODO
Examples
// TODO
Initializes an array containing the numbers in the specified range (in reverse) where start
and end
are inclusive with their common difference step
.
// TODO
Examples
// TODO
Initializes and fills an array with the specified values.
// TODO
Examples
// TODO
Create a n-dimensional array with given value.
// TODO
Examples
// TODO
Returns a list of elements that exist in both arrays.
// TODO
Examples
// TODO
Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.
// TODO
Examples
// TODO
Returns a list of elements that exist in both arrays, using a provided comparator function.
// TODO
Examples
// TODO
Returns 1
if the array is sorted in ascending order, -1
if it is sorted in descending order or 0
if it is not sorted.
// TODO
Examples
// TODO
Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.
// TODO
Examples
// TODO
Converts an array of objects to a comma-separated values (CSV) string that contains only the columns
specified.
// TODO
Examples
// TODO
Returns the last element in an array.
// TODO
Examples
// TODO
Takes any number of iterable objects or objects with a length
property and returns the longest one.
If multiple objects have the same length, the first one will be returned.
Returns -1
if no arguments are provided.
// TODO
Examples
// TODO
Returns the n
maximum elements from the provided array.
If n
is greater than or equal to the provided array's length, then return the original array (sorted in descending order).
// TODO
Examples
// TODO
Returns the n
minimum elements from the provided array.
If n
is greater than or equal to the provided array's length, then return the original array (sorted in ascending order).
// TODO
Examples
// TODO
Returns true
if the provided predicate function returns false
for all elements in a collection, false
otherwise.
// TODO
Examples
// TODO
Returns the nth element of an array.
// TODO
Examples
// TODO
Moves the specified amount of elements to the end of the array.
// TODO
Examples
// TODO
Sorts a collection of arrays.
// TODO
Examples
// TODO
Groups the elements into two arrays, depending on the provided function's truthiness for each element.
// TODO
Examples
// TODO
Generates all permutations of an array's elements (contains duplicates).
// TODO
Examples
// TODO
Retrieves all of the values for a given key.
// TODO
Examples
// TODO
Mutates the original array to filter out the values specified.
// TODO
Examples
// TODO
Mutates the original array to filter out the values at the specified indexes.
// TODO
Examples
// TODO
Mutates the original array to filter out the values specified. Returns the removed elements.
// TODO
Examples
// TODO
Mutates the original array to filter out the values specified, based on a given iterator function.
// TODO
Examples
// TODO
Filter an array of objects based on a condition while also filtering out unspecified keys.
// TODO
Examples
// TODO
Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values.
// TODO
Examples
// TODO
Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.
// TODO
Examples
// TODO
Takes a predicate and array, like Array.prototype.filter()
, but only keeps x
if pred(x) === false
.
// TODO
Examples
// TODO
Removes elements from an array for which the given function returns false
.
// TODO
Examples
// TODO
Returns a random element from an array.
// TODO
Examples
// TODO
Gets n
random elements at unique keys from array
up to the size of array
.
// TODO
Examples
// TODO
This method changes the contents of an array by removing existing elements and/or adding new elements.
Similar to the JavaScript version Array.prototype.splice()
// TODO
Examples
// TODO
Randomizes the order of the values of an array, returning a new array.
// TODO
Examples
// TODO
Returns an array of elements that appear in both arrays.
// TODO
Examples
// TODO
Returns the lowest index at which value should be inserted into array in order to maintain its sort order.
// TODO
Examples
// TODO
Returns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.
// TODO
Examples
// TODO
Returns the highest index at which value should be inserted into array in order to maintain its sort order.
// TODO
Examples
// TODO
Returns the highest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.
// TODO
Examples
// TODO
Performs stable sorting of an array, preserving the initial indexes of items when their values are the same. Does not mutate the original array, but returns a new array instead.
// TODO
Examples
// TODO
Returns the symmetric difference between two arrays, without filtering out duplicate values.
// TODO
Examples
// TODO
Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.
// TODO
Examples
// TODO
Returns the symmetric difference between two arrays, using a provided function as a comparator.
// TODO
Examples
// TODO
Returns all elements in an array except for the first one.
// TODO
Examples
// TODO
Returns an array with n elements removed from the beginning.
// TODO
Examples
// TODO
Returns an array with n elements removed from the end.
// TODO
Examples
// TODO
Removes elements from the end of an array until the passed function returns true
. Returns the removed elements.
// TODO
Examples
// TODO
Removes elements in an array until the passed function returns true
. Returns the removed elements.
// TODO
Examples
// TODO
Reduces a given Array-like into a value hash (keyed data store).
// TODO
Examples
// TODO
Returns every element that exists in any of the two arrays once.
// TODO
Examples
// TODO
Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both.
// TODO
Examples
// TODO
Returns every element that exists in any of the two arrays once, using a provided comparator function.
// TODO
Examples
// TODO
Returns all unique values of an array.
// TODO
Examples
// TODO
Returns all unique values of an array, based on a provided comparator function.
// TODO
Examples
// TODO
Returns all unique values of an array, based on a provided comparator function.
// TODO
Examples
// TODO
Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.
// TODO
Examples
// TODO
Filters out the elements of an array, that have one of the specified values.
// TODO
Examples
// TODO
Creates a new array out of the two supplied by creating each possible pair from the arrays.
// TODO
Examples
// TODO
Checks if two numbers are approximately equal to each other.
// TODO
Examples
// TODO
Returns the average of two or more numbers.
The method excepts numbers as params and returns the average as a result
Linq documentation https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sum?view=netframework-4.7.2
namespace conplement.snippets.Math
{
public static partial class Math
{
public static double Average(this uint[] elements)
{
if (elements.Length == 0) return 0;
return elements.Aggregate(0.0, (current, element) => current + element) / elements.Length;
}
}
}
Examples
{ 4, 5, 9, 1, 0 }.Average() # 3.8
Returns the average of an array, after mapping each element to a value using the provided function.
// TODO
Examples
// TODO
Evaluates the binomial coefficient of two integers n
and k
.
// TODO
Examples
// TODO
Converts an angle from degrees to radians.
// TODO
Examples
// TODO
Converts a number to an array of digits.
// TODO
Examples
// TODO
Returns the distance between two points.
// TODO
Examples
// TODO
Calculates the factorial of a number.
// TODO
Examples
// TODO
Generates an array, containing the Fibonacci sequence, up until the nth term.
// TODO
Examples
// TODO
Calculates the greatest common divisor between two or more numbers/arrays.
// TODO
Examples
// TODO
Initializes an array containing the numbers in the specified range where start
and end
are inclusive and the ratio between two terms is step
.
Returns an error if step
equals 1
.
// TODO
Examples
// TODO
Checks if the given number falls within the given range.
// TODO
Examples
// TODO
Checks if the first numeric argument is divisible by the second one.
// TODO
Examples
// TODO
Returns true
if the given number is even, false
otherwise.
// TODO
Examples
// TODO
Checks if the provided integer is a prime number.
// TODO
Examples
// TODO
Returns true
if the given number is odd, false
otherwise.
// TODO
Examples
// TODO
Returns the least common multiple of two or more numbers.
// TODO
Examples
// TODO
Implementation of the Luhn Algorithm used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.
// TODO
Examples
// TODO
Returns the maximum value from the provided enumerable.
// TODO
Examples
// TODO
Returns the median of an array of numbers.
// TODO
Examples
// TODO
Returns the minimum value from the provided enumerable.
// TODO
Examples
// TODO
Generates primes up to a given number, using the Sieve of Eratosthenes.
// TODO
Examples
// TODO
Converts an angle from radians to degrees.
// TODO
Examples
// TODO
Returns an array of n random integers in the specified range.
// TODO
Examples
// TODO
Returns a random integer in the specified range.
// TODO
Examples
// TODO
Returns a random number in the specified range.
// TODO
Examples
// TODO
Rounds a number to a specified amount of digits.
// TODO
Examples
// TODO
Hashes the input string into a whole number.
// TODO
Examples
// TODO
Returns the standard deviation of an array of numbers.
// TODO
Examples
// TODO
Returns the sum of two or more numbers/arrays.
// TODO
Examples
// TODO
Returns the sum of an array, after mapping each element to a value using the provided function.
// TODO
Examples
// TODO
Returns the number of times a function executed per second.
hz
is the unit for hertz
, the unit of frequency defined as one cycle per second.
// TODO
Examples
// TODO
Iterates over a callback n
times
namespace conplement.snippets.Method
{
public static partial class Method
{
public static IList<T1> Times<T1>(Func<T1> func, uint times)
{
var list = new List<T1>();
for (var index = 0; index < times; index++)
{
list.Add(func());
}
return list;
}
}
}
Examples
Method.Times((() => true), 3) # list of size 3, all values true
Method.Times(((int start, int end) => new Random().Next(start, end)), 6, 0, 100) # list of size 6 with 6 random integers between 0 and 100
Returns the length of a string in bytes.
// TODO
Examples
// TODO
Capitalizes the first letter of a string.
// TODO
Examples
// TODO
Capitalizes the first letter of every word in a string.
// TODO
Examples
// TODO
Returns number of vowels in provided string.
// TODO
Examples
// TODO
Converts a comma-separated values (CSV) string to a 2D array.
// TODO
Examples
// TODO
Converts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.
// TODO
Examples
// TODO
Decapitalizes the first letter of a string.
// TODO
Examples
// TODO
Check if a string is ends with a given substring using a regex
The method excepts the string to test and a regex
Most other checks are already integrated into C# https://docs.microsoft.com/en-us/dotnet/api/system.string.endswith?view=netframework-4.7.2
namespace conplement.snippets.String
{
public static partial class String
{
public static bool EndsWithRegex(this string input, Regex regex)
{
return regex.IsMatch(input);
}
}
}
Examples
"Hello World".EndsWithRegex(new Regex(@"[dolrwDOLRW]{5}$")) # true
Escapes a string for use in HTML.
// TODO
Examples
// TODO
Escapes a string to use in a regular expression.
// TODO
Examples
// TODO
Converts a string from camelcase.
// TODO
Examples
// TODO
Indents each line in the provided string.
// TODO
Examples
// TODO
Returns true
if the given string is an absolute URL, false
otherwise.
// TODO
Examples
// TODO
Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
// TODO
Examples
// TODO
Checks if a string is lower case.
// TODO
Examples
// TODO
Checks if a string is upper case.
// TODO
Examples
// TODO
Replaces all but the last num
of characters with the specified mask character.
// TODO
Examples
// TODO
Pads a string on both sides with the specified character, if it's shorter than the specified length.
// TODO
Examples
// TODO
Returns true
if the given string is a palindrome, false
otherwise.
// TODO
Examples
// TODO
Returns the singular or plural form of the word based on the input number. If the first argument is an object
, it will use a closure by returning a function that can auto-pluralize words that don't simply end in s
if the supplied dictionary contains the word.
// TODO
Examples
// TODO
Removes non-printable ASCII characters.
// TODO
Examples
// TODO
Reverses a string.
// TODO
Examples
// TODO
Alphabetically sorts the characters in a string.
// TODO
Examples
// TODO
Splits a multiline string into an array of lines.
// TODO
Examples
// TODO
Check if a string starts with a given regex.
// TODO
Examples
// TODO
Generates all permutations of a string (contains duplicates).
// TODO
Examples
// TODO
Removes HTML/XML tags from string.
// TODO
Examples
// TODO
Converts a string to camelcase.
// TODO
Examples
// TODO
Converts a string to kebab case.
// TODO
Examples
// TODO
Converts a string to snake case.
// TODO
Examples
// TODO
Converts a string to title case.
// TODO
Examples
// TODO
Truncates a string up to a specified length.
// TODO
Examples
// TODO
Unescapes escaped HTML characters.
// TODO
Examples
// TODO
Joins all given URL segments together, then normalizes the resulting URL
// TODO
Examples
// TODO
Converts a given string into an array of words.
// TODO
Examples
// TODO
Checks if the provided value is of the specified type.
// TODO
Examples
// TODO
Checks if the provided argument is a valid JSON.
// TODO
Examples
// TODO
Returns the first non-null argument.
// TODO
Examples
// TODO
Extends a 3-digit color code to a 6-digit color code.
// TODO
Examples
// TODO
Returns an object containing the parameters of the current URL.
// TODO
Examples
// TODO
Converts a color code to a rgb()
or rgba()
string if alpha value is provided.
// TODO
Examples
// TODO
Returns the index of the function in an array of functions which executed the fastest.
// TODO
Examples
// TODO
Converts a number in bytes to a human-readable string.
// TODO
Examples
// TODO
Generates a random hexadecimal color code.
// TODO
Examples
// TODO
Converts the values of RGB components to a color code.
// TODO
Examples
// TODO
Measures the time taken by a function to execute.
Stopwatch documentation https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?redirectedfrom=MSDN&view=netframework-4.7.2
namespace conplement.snippets.Utility
{
public static partial class Utility
{
public static (long, T1) TimeTaken<T1>(Func<T1> func)
{
var watch = Stopwatch.StartNew();
T1 result = func.Invoke();
watch.Stop();
return (watch.ElapsedMilliseconds, result);
}
}
}
Examples
Utility.TimeTaken(() => true) # 13.37ms, true
Adds an ordinal suffix to a number.
// TODO
Examples
// TODO
Returns true
if the string is y
/yes
or false
if the string is n
/no
.
// TODO
Examples
// TODO
You're always welcome to contribute to this project. Please read the contribution guide.
This project is licensed under the MIT License - see the License File for details