30-seconds-of-c-sharp
30-seconds-of-c-sharp copied to clipboard
A curated collection of useful C# snippets that you can understand in 30 seconds or less.
Support me
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.
Official 30 Seconds of * projects
- 30 Seconds of Code
- 30 Seconds of CSS
- 30 Seconds of Interviews
- 30 Seconds of React
- 30 Seconds of Python
- 30 Seconds of PHP
- 30 Seconds of Knowledge
Unofficial 30 Seconds of * projects
Table of Contents
β±οΈ Date
View contents
-
dayOfYear
-
formatDuration
-
getColonTimeFromDate
-
getDaysDiffBetweenDates
-
getMeridiumSuffixOfInteger
-
isAfterDate
-
isBeforeDate
-
isSameDate
-
maxDate
-
minDate
-
tomorrow
π Enumerable
View contents
-
allEqual
-
bifurcate
-
bubbleSort
-
chunk
-
compact
-
countBy
-
countOccurences
-
deepFlatten
-
difference
-
differenceSelect
-
differenceWhere
-
drop
-
dropRight
-
dropRightWhile
-
dropWhile
-
everyNth
-
filterNonUnique
-
filterNonUniqueBy
-
findLast
-
findLastIndex
-
flatten
-
forEachRight
-
hasDuplicates
-
indexOfAll
-
initial
-
initialize2DArray
-
initializeArrayWithRange
-
initializeArrayWithRangeRight
-
initializeArrayWithValues
-
initializeNDArray
-
intersection
-
intersectionSelect
-
intersectionWhere
-
jsonToCsv
-
longestItem
-
maxN
-
minN
-
none
-
nthElement
-
offset
-
orderBy
-
partition
-
permutations
-
pluck
-
pull
-
pullAtIndex
-
pullAtValue
-
pullBy
-
reduceFilter
-
reduceSuccessive
-
reduceWhich
-
reject
-
remove
-
sample
-
sampleSize
-
shank
-
shuffle
-
similarity
-
sortedDirection
-
sortedIndex
-
sortedIndexBy
-
sortedLastIndex
-
sortedLastIndexBy
-
stableSort
-
symmetricDifference
-
symmetricDifferenceBy
-
symmetricDifferenceWith
-
tail
-
take
-
takeRight
-
takeRightWhile
-
takeWhile
-
toCsv
-
toHash
-
union
-
unionBy
-
unionWith
-
uniqueElements
-
uniqueElementsBy
-
uniqueElementsByRight
-
uniqueSymmetricDifference
-
without
-
xProd
β Math
View contents
-
approximatelyEqual
-
average
-
averageBy
-
binomialCoefficient
-
degToRads
-
digitize
-
distance
-
factorial
-
fibonacci
-
gcd
-
geometricProgression
-
inRange
-
isDivisibleBy
-
isEven
-
isPrime
-
isOdd
-
lcm
-
luhnCheck
-
max
-
median
-
min
-
primes
-
radToDeg
-
randomIntArrayInRange
-
randomIntegerInRange
-
randomNumberInRange
-
round
-
sdbm
-
standardDeviation
-
sum
-
sumBy
ποΈ Method
View contents
-
hz
-
times
π String
View contents
-
byteSize
-
countVowels
-
csvToArray
-
csvToJson
-
endsWithRegex
-
fromCamelCase
-
isAnagramOf
-
isLower
-
isPalindrome
-
isUpper
-
mask
-
pad
-
removeNonAscii
-
reverse
-
splitLines
-
startsWithRegex
-
stripHtmlTags
-
toCamelCase
-
toKebabCase
-
toSnakeCase
-
toTitleCase
-
truncate
-
words
ποΈ Type
View contents
-
isNumericType
π§ Utility
View contents
-
extendHex
-
hexToRgb
-
prettyBytes
-
randomHexColor
-
rgbToHex
-
timeTaken
-
yesNo
β±οΈ Date
dayOfYear
Returns the day of the current year.
Already integrated here.
using System;
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static int DayOfYear()
{
return DateTime.UtcNow.DayOfYear;
}
}
}
Examples
JonasSchubert.Snippets.Date.DayOfYear() # 12/31/2016: day 366 of 2016 (Leap Year)
β Back to top
formatDuration
Returns the human readable format of the given number of milliseconds.
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static string FormatDuration(ulong milliseconds)
{
var dictionary = new Dictionary<string, Tuple<ulong, uint>>
{
{ "week", new Tuple<ulong, uint>(7* 24 * 60 * 60 * 1000, int.MaxValue) },
{ "day", new Tuple<ulong, uint>(24 * 60 * 60 * 1000, 7) },
{ "hour", new Tuple<ulong, uint>(60 * 60 * 1000, 24) },
{ "minute", new Tuple<ulong, uint>(60 * 1000, 60) },
{ "second", new Tuple<ulong, uint>(1000, 60) },
{ "millisecond", new Tuple<ulong, uint>(1, 1000) }
};
var stringArray = dictionary
.Select(item =>
((milliseconds / item.Value.Item1) % item.Value.Item2) > 0
? $"{((milliseconds / item.Value.Item1) % item.Value.Item2)} {item.Key}{(((milliseconds / item.Value.Item1) % item.Value.Item2) > 1 ? "s" : string.Empty)}"
: string.Empty)
.Where(x => !string.IsNullOrEmpty(x))
.ToArray();
return stringArray.Length > 0
? string.Join(", ", stringArray)
: "0 millisecond";
}
}
}
Examples
var actual = Date.FormatDuration(34325055574ul); # "56 weeks, 5 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds"
β Back to top
getColonTimeFromDate
Returns a string of the form HH:MM:SS
from a DateTime
or TimeSpan
object.
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static string GetColonTimeFromDate(this DateTime dateTime)
{
return $"{dateTime.Hour.ToString("D2")}:{dateTime.Minute.ToString("D2")}:{dateTime.Second.ToString("D2")}";
}
public static string GetColonTimeFromDate(this TimeSpan timeSpan)
{
return $"{timeSpan.Hours.ToString("D2")}:{timeSpan.Minutes.ToString("D2")}:{timeSpan.Seconds.ToString("D2")}";
}
}
}
Examples
new DateTime(2018, 11, 22, 17, 53, 23).GetColonTimeFromDate() # 17:53:23
new DateTime(1990, 1, 2, 3, 41, 5).GetColonTimeFromDate() # 03:41:05
new TimeSpan(1, 33, 7).GetColonTimeFromDate() # 01:33:07
β Back to top
getDaysDiffBetweenDates
Returns the difference (in days) between two dates.
using System;
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static double GetDaysDiffBetweenDates(DateTime dateTime1, DateTime dateTime2)
{
if (dateTime1.Kind != dateTime2.Kind)
{
throw new ArgumentException($"The DateTime values have to be in the same timezone! {nameof(dateTime1)} uses {dateTime1.Kind}, while {nameof(dateTime2)} uses {dateTime2.Kind}!");
}
return (dateTime1 - dateTime2).TotalDays;
}
}
}
Examples
Date.GetDaysDiffBetweenDates(new DateTime(2018, 11, 22), new DateTime(2018, 11, 14)); # 8.0
β Back to top
getMeridiumSuffixOfInteger
Converts an integer to a suffixed string, adding am
or pm
based on its value.
using System;
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static string GetMeridiemSuffixOfInteger(this int value)
{
if (value < 0 || value > 24)
{
throw new ArgumentOutOfRangeException($"Invalid value {value} in method {nameof(GetMeridiemSuffixOfInteger)}", nameof(value));
}
return value == 0 || value == 24
? "12am" : value == 12
? "12pm" : value < 12
? $"{value % 12}am" : $"{value % 12}pm";
}
}
}
Examples
0.GetMeridiemSuffixOfInteger(); # 12am
11.GetMeridiemSuffixOfInteger(); # 11am
13.GetMeridiemSuffixOfInteger(); # 1pm
18.GetMeridiemSuffixOfInteger(); # 6pm
24.GetMeridiemSuffixOfInteger(); # 12am
β Back to top
isAfterDate
Check if a date is after another date.
using System;
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static bool IsAfterDate(this DateTime dateTime1, DateTime dateTime2)
{
if (dateTime1.Kind != dateTime2.Kind)
{
throw new ArgumentException($"The DateTime values have to be in the same timezone! {nameof(dateTime1)} uses {dateTime1.Kind}, while {nameof(dateTime2)} uses {dateTime2.Kind}!");
}
return dateTime1 > dateTime2;
}
}
}
Examples
DateTime(2018, 11, 21).IsAfterDate(new DateTime(2018, 11, 22)) # false
β Back to top
isBeforeDate
Check if a date is before another date.
using System;
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static bool IsBeforeDate(this DateTime dateTime1, DateTime dateTime2)
{
if (dateTime1.Kind != dateTime2.Kind)
{
throw new ArgumentException($"The DateTime values have to be in the same timezone! {nameof(dateTime1)} uses {dateTime1.Kind}, while {nameof(dateTime2)} uses {dateTime2.Kind}!");
}
return dateTime1 < dateTime2;
}
}
}
Examples
DateTime(2018, 11, 21).IsBeforeDate(new DateTime(2018, 11, 22)) # true
β Back to top
isSameDate
Check if a date is the same as another date.
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static bool IsSameDate(this DateTime dateTime1, DateTime dateTime2)
{
return dateTime1 == dateTime2 && dateTime1.Kind == dateTime2.Kind;
}
}
}
Examples
var actual = new DateTime(2018, 11, 26).IsSameDate(new DateTime(2018, 11, 26)); # true
var actual = new DateTime(203940201L).IsSameDate(new DateTime(203940202L)); # false
β Back to top
maxDate
Returns the maximum of the given dates.
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static DateTime MaxDate(params DateTime[] dateTimeList)
{
if (dateTimeList == null || !dateTimeList.Any())
{
throw new ArgumentException("The dateTimeList may not be empty!", nameof(dateTimeList));
}
if (!dateTimeList.All(x => dateTimeList.First().Kind == x.Kind))
{
throw new ArgumentException("All params have to have the same timezone!", nameof(dateTimeList));
}
return dateTimeList.Max();
}
}
}
Examples
DateTime[] list = { new DateTime(2018, 11, 27, 22, 2, 15), new DateTime(2018, 11, 27, 22, 2, 15), new DateTime(2018, 11, 27), new DateTime(2019) };
var actual = Date.MaxDate(list); # new DateTime(2019)
β Back to top
minDate
Returns the minimum of the given dates.
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static DateTime MinDate(params DateTime[] dateTimeList)
{
if (dateTimeList == null || !dateTimeList.Any())
{
throw new ArgumentException("The dateTimeList may not be empty!", nameof(dateTimeList));
}
if (!dateTimeList.All(x => dateTimeList.First().Kind == x.Kind))
{
throw new ArgumentException("All params have to have the same timezone!", nameof(dateTimeList));
}
return dateTimeList.Min();
}
}
}
Examples
DateTime[] list = { new DateTime(2018, 11, 27, 22, 2, 15), new DateTime(2018, 11, 27, 22, 2, 15), new DateTime(2018, 11, 27), new DateTime(2018) };
var actual = Date.MinDate(list); # new DateTime(2018)
β Back to top
tomorrow
Returns tomorrow's date.
namespace JonasSchubert.Snippets.Date
{
public static partial class Date
{
public static DateTime Tomorrow(DateTimeKind dateTimeKind = DateTimeKind.Utc)
{
return (dateTimeKind == DateTimeKind.Local
? DateTime.Now
: DateTime.UtcNow)
+ TimeSpan.FromDays(1);
// Instead of TimeSpan you can also use https://github.com/TimeXt/FluentTimeSpan to add one day like tomorrow = DateTime.UtcNow + 1.Days()
}
}
}
Examples
var actual = Date.Tomorrow(DateTimeKind.Local); # If today is 15.05.2019, it will return 16.05.2019
β Back to top
π Enumerable
allEqual
Check if all elements in an array are equal.
using System;
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static bool AllEqual<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
var testList = enumerable.ToList();
if (testList.Count <= 1)
{
return true;
}
var compareObject = testList[0];
for (int index = 0; index < testList.Count; index++)
{
var entry = testList[index];
if ((entry == null || !entry.Equals(compareObject))
&& !(entry == null && compareObject == null))
{
return false;
}
}
return true;
}
}
}
Examples
new double[] { 1.25, 1.25, 1.5, -1.5 }.AllEqual(); # false
β Back to top
bifurcate
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.
using System;
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static (IEnumerable<T>, IEnumerable<T>) Bifurcate<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));
}
IEnumerable<T> enumerable1 = list.Where(filter);
IEnumerable<T> enumerable2 = list.Where(x => !enumerable1.Any(y => y.Equals(x)));
return (enumerable1, enumerable2);
}
}
}
Examples
var list = new List<int>
{
1, 2, 3, 4, 1
};
(IEnumerable<int> actual1, IEnumerable<int> actual2) = list.Bifurcate(x => x > 1); # actual1 has three entries (2, 3, 4), actual2 has two entries (1, 1)
β Back to top
bubbleSort
bubbleSort uses the technique of comparing and swapping
// TODO
Examples
// TODO
β Back to top
chunk
Chunks an enumerable into smaller lists of a specified size.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static List<List<T>> Chunk<T>(this IEnumerable<T> enumerable, int size)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (size <= 0)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
var list = new List<List<T>>();
var startIndex = 0;
while (startIndex < enumerable.Count())
{
list.Add(enumerable.Skip(startIndex).Take(size).ToList());
startIndex += size;
}
return list;
}
}
}
Examples
new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" }.Chunk(6); # will result in two new string arrays => new string[]][] { new string[] { "1", "2", "3", "4", "5", "6" }, new string[] { "7", "8", "9", "10", "11" }}
new int[] { 0, 1, 2 }.Chunk(6); # will result in one integer array => new int[][] { new int[] { 0, 1, 2 } }
β Back to top
compact
Removes invalid values from an array.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<T> Compact<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (!enumerable.Any())
{
yield break;
}
foreach (var element in enumerable)
{
switch (element)
{
case string y:
if (string.IsNullOrEmpty(y))
{
continue;
}
yield return element;
break;
case bool y:
if (!y)
{
continue;
}
yield return element;
break;
case byte y:
if (y == 0)
{
continue;
}
yield return element;
break;
// ... more definitions necessary, Please have a look into the code
default:
if (element == null)
{
continue;
}
yield return element;
break;
}
}
}
}
}
Examples
var enumerable = new List<object> { new object(), null, new object(), new object(), null, false, true, 1, 0, "Hello", "", "World" }.Compact(); # List with seven entries: new List<object> { new object(), new object(), new object(), true, 1, "Hello", "World" };
β Back to top
countBy
Groups the elements of an enumerable based on the given function and returns the count of elements in each group as dictionary, objects as key and count of object as value (uint). Elements may not be null!
using System;
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IDictionary<T, uint> CountBy<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
var dictionary = new Dictionary<T, uint>();
foreach (var key in enumerable)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (dictionary.ContainsKey(key))
{
dictionary[key]++;
}
else
{
dictionary.Add(key, 1u);
}
}
return dictionary;
}
}
}
Examples
new List<int> { 1, 2, 3, 2, 1 }.CountBy(); # new Dictionary<int, uint> { { 1, 2u }, { 2, 2u }, { 3, 1u } };
β Back to top
countOccurrences
Counts the occurrences of a value in an enumerable.
using System;
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static int CountOccurences<T>(this IEnumerable<T> enumerable, T value)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
return enumerable.Count(x => x.Equals(value));
}
}
}
Examples
new string[] { "Hello", "Hello", "Hello", "World", "Hello", "", string.Empty }.CountOccurences("Hello"); # 4
β Back to top
deepFlatten
Deep flattens an array of arrays.
// TODO
Examples
// TODO
β Back to top
difference
Returns the difference between two enumerables.
using System;
namespace JonasSchubert.Snippets.Enumerable
{
public static IEnumerable<T> Difference<T>(this IEnumerable<T> enumerable1, IEnumerable<T> enumerable2)
{
if (enumerable1 == null)
{
throw new ArgumentNullException(nameof(enumerable1));
}
if (enumerable2 == null)
{
throw new ArgumentNullException(nameof(enumerable2));
}
return enumerable1.Where(x => !enumerable2.Any(y => x.Equals(y))).Concat(enumerable2.Where(x => !enumerable1.Any(y => x.Equals(y))));
}
}
Examples
new List<int>{ 1, 2, 3, 4, 0}.Difference(new List<int>{ 1, 5, 3, 4, 1 }); # new List<int>{ 2, 0, 5}
β Back to top
differenceSelect
Returns the difference between two enumerables, after applying the provided function to each enumerable element of both.
using System;
namespace JonasSchubert.Snippets.Enumerable
{
public static IEnumerable<K> DifferenceSelect<T, K>(this IEnumerable<T> enumerable1, IEnumerable<T> enumerable2, Func<T, K> selectFunction)
{
if (enumerable1 == null)
{
throw new ArgumentNullException(nameof(enumerable1));
}
if (enumerable2 == null)
{
throw new ArgumentNullException(nameof(enumerable2));
}
if (selectFunction == null)
{
throw new ArgumentNullException(nameof(selectFunction));
}
var selectedEnumerable1 = enumerable1.Select(selectFunction);
var selectedEnumerable2 = enumerable2.Select(selectFunction);
return selectedEnumerable1.Where(x => !selectedEnumerable2.Any(y => x.Equals(y))).Concat(selectedEnumerable2.Where(x => !selectedEnumerable1.Any(y => x.Equals(y))));
}
}
Examples
new List<int>{ 1, 2, 3, 4, 0}.DifferenceSelect(new List<int>{ 1, 5, 3, 4, 1 }, x => x); # new List<int>{ 2, 0, 5}
β Back to top
differenceWhere
Filters out all values from an array for which the comparator function does not return true
.
using System;
namespace JonasSchubert.Snippets.Enumerable
{
public static IEnumerable<T> DifferenceWhere<T>(this IEnumerable<T> enumerable1, IEnumerable<T> enumerable2, Func<T, bool> whereFunction)
{
if (enumerable1 == null)
{
throw new ArgumentNullException(nameof(enumerable1));
}
if (enumerable2 == null)
{
throw new ArgumentNullException(nameof(enumerable2));
}
if (whereFunction == null)
{
throw new ArgumentNullException(nameof(whereFunction));
}
var selectedEnumerable1 = enumerable1.Where(whereFunction);
var selectedEnumerable2 = enumerable2.Where(whereFunction);
return selectedEnumerable1.Where(x => !selectedEnumerable2.Any(y => x.Equals(y))).Concat(selectedEnumerable2.Where(x => !selectedEnumerable1.Any(y => x.Equals(y))));
}
}
Examples
new List<int>{ 1, 2, 3, 4, 0}.DifferenceWhere(new List<int>{ 1, 5, 3, 4, 1 }, x => x > 1); # new List<int>{ 2, 5}
β Back to top
drop
Returns a new array with n
elements removed from the left.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<T> Drop<T>(this IEnumerable<T> enumerable, uint dropCount)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (enumerable.Count() < dropCount)
{
throw new ArgumentOutOfRangeException(nameof(enumerable));
}
return enumerable.Skip((int)dropCount);
}
}
}
Examples
var enumerable = new bool[] { false, false, true, true }.Drop(3); # List with one entry: true
β Back to top
dropRight
Returns a new array with n
elements removed from the right.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<T> Drop<T>(this IEnumerable<T> enumerable, uint dropCount)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (enumerable.Count() < dropCount)
{
throw new ArgumentOutOfRangeException(nameof(enumerable));
}
return enumerable.Take(enumerable.Count() - (int)dropCount);
}
}
}
Examples
var enumerable = new bool[] { false, false, true, true }.DropRight(3); # List with one entry: false
β Back to top
dropRightWhile
Removes elements from the end of an array until the passed function returns true
. Returns the remaining elements in the array.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<T> DropRightWhile<T>(this IEnumerable<T> enumerable, Func<T, bool> filter)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (filter == null)
{
throw new ArgumentNullException(nameof(filter));
}
var reachedDropPoint = false;
for (var index = enumerable.Count() - 1; index >= 0; index--)
{
var element = enumerable.ElementAt(index);
if (!reachedDropPoint && !filter(element))
{
continue;
}
reachedDropPoint = true;
yield return element;
}
yield break;
}
}
}
Examples
var enumerable = new int[] { 1, 2, 3, 4, 1 }.DropRightWhile(x => x > 2); # List with four entries: new List<int> { 1, 2, 3, 4 }
β Back to top
dropWhile
Removes elements in an array until the passed function returns true
. Returns the remaining elements in the array.
namespace JonasSchubert.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 }
β Back to top
everyNth
Returns every nth element in an enumerable.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<T> EveryNth<T>(this IEnumerable<T> enumerable, uint nth)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (nth == 0u)
{
throw new ArgumentNullException(nameof(nth));
}
for (var index = nth - 1; index < enumerable.Count(); index += nth)
{
yield return enumerable.ElementAt((int)index);
}
}
}
}
Examples
new List<int>{ 1, 2, 3, 4, 1}.EveryNth(3u); # new List<int> { 3 }
β Back to top
filterNonUnique
Filters out the non-unique not null values in an enumerable.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<T> FilterNonUnique<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
for (var index = 0; index < enumerable.Count(); index++)
{
if (enumerable.Where(x => x != null && x.Equals(enumerable.ElementAt(index))).Count() == 1)
{
yield return enumerable.ElementAt(index);
}
}
}
}
}
Examples
new string[] { "Hello", "world", "organisation", "seconds", "of", "organisation" }.FilterNonUnique(); # new string[] { "Hello", "world", "seconds", "of" }
β Back to top
filterNonUniqueBy
Filters out the non-unique not null values in an enumerable, based on a provided comparator function (where linq statement).
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<T> FilterNonUniqueWhere<T>(this IEnumerable<T> enumerable, Func<T, bool> whereFunction)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (whereFunction == null)
{
throw new ArgumentNullException(nameof(whereFunction));
}
for (var index = 0; index < enumerable.Count(); index++)
{
if (enumerable.Where(whereFunction).Where(x => x != null && x.Equals(enumerable.ElementAt(index))).Count() == 1)
{
yield return enumerable.ElementAt(index);
}
}
}
}
}
Examples
new string[] { "Hello", "world", "organisation", "seconds", "of", "organisation" }.FilterNonUniqueWhere(x => x != "world"); # new string[] { "Hello", "seconds", "of" }
β Back to top
findLast
Returns the last element for which the provided function returns a truthy value.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static T FindLast<T>(this IEnumerable<T> enumerable, Func<T, bool> whereFunction)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (whereFunction == null)
{
throw new ArgumentNullException(nameof(whereFunction));
}
return enumerable.Where(whereFunction).Reverse().FirstOrDefault();
}
}
}
Examples
new List<int> { 1, 2, 3, 4, 0 }.FindLast(x => x % 4 == 0 && x != 0); # 4
β Back to top
findLastIndex
Returns the index of the last element for which the provided function returns a truthy value. Returns -1 if nothing found at all.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static int FindLastIndex<T>(this IEnumerable<T> enumerable, Func<T, bool> whereFunction)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (whereFunction == null)
{
throw new ArgumentNullException(nameof(whereFunction));
}
var foundElement = enumerable.Where(whereFunction).Reverse().FirstOrDefault();
if (foundElement == null)
{
return -1;
}
for (var index = enumerable.Count() - 1; index > -1; index--)
{
if (enumerable.ElementAt(index).Equals(foundElement))
{
return index;
}
}
throw new InvalidOperationException(nameof(FindLastIndex));
}
}
}
Examples
new List<int> { 1, 2, 3, 4, 0 }.FindLastIndex(x => x % 4 == 0 && x != 0); # 3
β Back to top
flatten
Flattens an array up to the specified depth.
// TODO
Examples
// TODO
β Back to top
forEachRight
Executes a provided function once for each enumerable element, starting from the enumerable's last element.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static void ForEachRight<T>(this IEnumerable<T> enumerable, Action<T> function)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (function == null)
{
throw new ArgumentNullException(nameof(function));
}
foreach (var element in enumerable.Reverse())
{
function(element);
}
}
}
}
Examples
var testString = "";
new string[] { "world", "Hello" }.ForEachRight((string x) => testString = testString + " " + x); # " Hello world"
β Back to top
hasDuplicates
Checks an enumerable for duplicate values. Returns true if duplicate values exist and false if values are all unique.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static bool HasDuplicates<T>(this IEnumerable<T> enumerable) =>
enumerable == null
? throw new ArgumentNullException(nameof(enumerable))
: enumerable.Count() != enumerable.Distinct().Count();
}
}
Examples
new List<uint> { 1u, 2u, 3u, 4u, 0u, 1u }.HasDuplicates(); # true
new string[] { "Hello", "world", "organisation", "seconds", "of" }.HasDuplicates(); # false
β Back to top
indexOfAll
Returns all indices of a value in an enumerable. If the value never occurs, returns empty.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<int> IndexOfAll<T>(this IEnumerable<T> enumerable, Func<T, bool> whereFunction)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (whereFunction == null)
{
throw new ArgumentNullException(nameof(whereFunction));
}
var foundElements = enumerable.Where(whereFunction);
if (foundElements.Any())
{
for (var index = 0; index < enumerable.Count(); index++)
{
if (foundElements.Any(x => x.Equals(enumerable.ElementAt(index))))
{
yield return index;
}
}
}
}
}
}
Examples
new List<bool?> { false, false, false, false, false, false, false, false, false }.IndexOfAll(x => x == true); # empty enumerable
new string[] { "Hello", "world", "organisation", "seconds", "or" }.IndexOfAll(x => x.Contains("or")); # new List<int> { 1, 2, 4 };
β Back to top
initial
Returns all the elements of an array except the last one.
// TODO
Examples
// TODO
β Back to top
initialize2DArray
Initializes a 2D array of given width and height and value.
namespace JonasSchubert.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 } }
β Back to top
initializeArrayWithRange
Initializes an array containing the numbers in the specified range where start
and end
are inclusive with their common difference step
.
// TODO
Examples
// TODO
β Back to top
initializeArrayWithRangeRight
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
β Back to top
initializeArrayWithValues
Initializes and fills an array with the specified values.
// TODO
Examples
// TODO
β Back to top
initializeNDArray
Create a n-dimensional array with given value.
// TODO
Examples
// TODO
β Back to top
intersection
Returns an enumerable of elements that exist in both enumerables.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<T> Intersection<T>(this IEnumerable<T> enumerable1, IEnumerable<T> enumerable2)
{
if (enumerable1 == null)
{
throw new ArgumentNullException(nameof(enumerable1));
}
if (enumerable2 == null)
{
throw new ArgumentNullException(nameof(enumerable2));
}
return enumerable1.Where(x => enumerable2.Any(y => x.Equals(y))).Concat(enumerable2.Where(x => enumerable1.Any(y => x.Equals(y)))).Distinct();
}
}
}
Examples
new string[] { "Hello", "world", "organisation", "seconds", "of", "Hello" }.Intersection(new string[] { "of", "organisation", "GuepardoApps", "Hello", "of" }); # new string[] { "Hello", "organisation", "of" }
β Back to top
intersectionSelect
Returns an enumerable of elements that exist in both enumerables, after applying the provided function to each enumerable element of both.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<K> IntersectionSelect<T, K>(this IEnumerable<T> enumerable1, IEnumerable<T> enumerable2, Func<T, K> selectFunction)
{
if (enumerable1 == null)
{
throw new ArgumentNullException(nameof(enumerable1));
}
if (enumerable2 == null)
{
throw new ArgumentNullException(nameof(enumerable2));
}
if (selectFunction == null)
{
throw new ArgumentNullException(nameof(selectFunction));
}
var selectedEnumerable1 = enumerable1.Select(selectFunction);
var selectedEnumerable2 = enumerable2.Select(selectFunction);
return selectedEnumerable1.Where(x => selectedEnumerable2.Any(y => x.Equals(y))).Concat(selectedEnumerable2.Where(x => selectedEnumerable1.Any(y => x.Equals(y)))).Distinct();
}
}
}
Examples
new string[] { "Hello", "world", "organisation", "seconds", "of", "of" }.IntersectionSelect(new string[] { "of", "organisation", "GuepardoApps", "Hello", "of" }, x => x); # new string[] { "Hello", "organisation", "of" }
β Back to top
intersectionWhere
Returns an enumerable of elements that exist in both enumerables, using a provided comparator function.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static IEnumerable<T> IntersectionWhere<T>(this IEnumerable<T> enumerable1, IEnumerable<T> enumerable2, Func<T, bool> whereFunction)
{
if (enumerable1 == null)
{
throw new ArgumentNullException(nameof(enumerable1));
}
if (enumerable2 == null)
{
throw new ArgumentNullException(nameof(enumerable2));
}
if (whereFunction == null)
{
throw new ArgumentNullException(nameof(whereFunction));
}
var selectedEnumerable1 = enumerable1.Where(whereFunction);
var selectedEnumerable2 = enumerable2.Where(whereFunction);
return selectedEnumerable1.Where(x => selectedEnumerable2.Any(y => x.Equals(y))).Concat(selectedEnumerable2.Where(x => selectedEnumerable1.Any(y => x.Equals(y)))).Distinct();
}
}
}
Examples
new string[] { "Hello", "world", "organisation", "seconds", "of" }.IntersectionWhere(new string[] { "of", "organisation", "GuepardoApps", "Hello", "of" }, x => x.Contains("or")); # new string[] { "organisation" }
β Back to top
jsonToCsv
Converts an array of objects to a comma-separated values (CSV) string that contains only the columns
specified.
// TODO
Examples
// TODO
β Back to top
longestItem
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
β Back to top
maxN
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
β Back to top
minN
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
β Back to top
none
Returns true
if the provided predicate function returns false
for all elements in a collection, false
otherwise.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static bool None<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
{
try
{
return enumerable.First(predicate) == null;
}
catch (Exception)
{
return true;
}
}
}
}
Examples
new List<int> { 3, 2, 0 }.None(x => x == 1); # true
new string[] { "Hello", "World" }.None(x => x.Length == 6) # true
new bool[] { true, false }.None(x => !x); # false
β Back to top
nthElement
Returns the nth element of an array.
// TODO
Examples
// TODO
β Back to top
offset
Moves the specified amount of elements to the end of the array.
// TODO
Examples
// TODO
β Back to top
orderBy
Sorts a collection of arrays.
// TODO
Examples
// TODO
β Back to top
partition
Groups the elements into two arrays, depending on the provided function's truthiness for each element.
// TODO
Examples
// TODO
β Back to top
permutations
β οΈ WARNING: This function's execution time increases exponentially with each array element.
Generates all permutations of an array's elements (contains duplicates).
// TODO
Examples
// TODO
β Back to top
pluck
Retrieves all of the values for a given key.
// TODO
Examples
// TODO
β Back to top
pull
Mutates the original array to filter out the values specified.
// TODO
Examples
// TODO
β Back to top
pullAtIndex
Mutates the original array to filter out the values at the specified indexes.
// TODO
Examples
// TODO
β Back to top
pullAtValue
Mutates the original array to filter out the values specified. Returns the removed elements.
// TODO
Examples
// TODO
β Back to top
pullBy
Mutates the original array to filter out the values specified, based on a given iterator function.
// TODO
Examples
// TODO
β Back to top
reduceFilter
Filter an array of objects based on a condition while also filtering out unspecified keys.
// TODO
Examples
// TODO
β Back to top
reduceSuccessive
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
β Back to top
reduceWhich
Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.
// TODO
Examples
// TODO
β Back to top
reject
Takes a predicate and array, like Array.prototype.filter()
, but only keeps x
if pred(x) === false
.
// TODO
Examples
// TODO
β Back to top
remove
Removes elements from an array for which the given function returns false
.
// TODO
Examples
// TODO
β Back to top
sample
Returns a random element from an array.
// TODO
Examples
// TODO
β Back to top
sampleSize
Gets n
random elements at unique keys from array
up to the size of array
.
// TODO
Examples
// TODO
β Back to top
shank
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
β Back to top
shuffle
Randomizes the order of the values of an array, returning a new array.
// TODO
Examples
// TODO
β Back to top
similarity
Returns an array of elements that appear in both arrays.
// TODO
Examples
// TODO
β Back to top
sortedDirection
Returns Direction.Ascending
if the enumerable is sorted in ascending order, Direction.Descending
if it is sorted in descending order or Direction.NotSorted
if it is not sorted or has only one value.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static Direction SortedDirection<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
if (enumerable.Count() <= 1)
{
return Direction.NotSorted;
}
var direction = enumerable.GetDirection(0, 1);
if (enumerable.Count() > 2)
{
for (var index = 2; index < enumerable.Count(); index++)
{
var currentDirection = enumerable.GetDirection(index - 1, index);
direction = direction == Direction.NotSorted ? currentDirection : direction;
if (direction != currentDirection)
{
return Direction.NotSorted;
}
}
}
return direction;
}
private static Direction GetDirection<T>(this IEnumerable<T> enumerable, int indexStart, int indexEnd)
{
var compareResult = Comparer<T>.Default.Compare(enumerable.ElementAt(indexStart), enumerable.ElementAt(indexEnd));
return compareResult < 0 ? Direction.Ascending : compareResult > 0 ? Direction.Descending : Direction.NotSorted;
}
}
}
Uses enum JonasSchubert.Snippets.Enumerable.Direction.
public enum Direction
{
NotSorted,
Ascending,
Descending
}
Examples
new List<uint> { 1, 2, 3, 4, 5 }.SortedDirection(); # Direction.Ascending
new string[] { "C", "B", "A" }.SortedDirection(); # Direction.Descending
new List<TestStruct>() { new TestStruct { Byte = 0 }, new TestStruct { Byte = 1 }, new TestStruct { Byte = 0 } }.SortedDirection(); # Direction.NotSorted
β Back to top
sortedIndex
Returns the lowest index at which value should be inserted into array in order to maintain its sort order.
// TODO
Examples
// TODO
β Back to top
sortedIndexBy
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
β Back to top
sortedLastIndex
Returns the highest index at which value should be inserted into array in order to maintain its sort order.
// TODO
Examples
// TODO
β Back to top
sortedLastIndexBy
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
β Back to top
stableSort
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
β Back to top
symmetricDifference
Returns the symmetric difference between two arrays, without filtering out duplicate values.
// TODO
Examples
// TODO
β Back to top
symmetricDifferenceBy
Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.
// TODO
Examples
// TODO
β Back to top
symmetricDifferenceWith
Returns the symmetric difference between two arrays, using a provided function as a comparator.
// TODO
Examples
// TODO
β Back to top
tail
Returns all elements in an array except for the first one.
// TODO
Examples
// TODO
β Back to top
take
Returns an array with n elements removed from the beginning.
// TODO
Examples
// TODO
β Back to top
takeRight
Returns an array with n elements removed from the end.
// TODO
Examples
// TODO
β Back to top
takeRightWhile
Removes elements from the end of an array until the passed function returns true
. Returns the removed elements.
// TODO
Examples
// TODO
β Back to top
takeWhile
Removes elements in an array until the passed function returns true
. Returns the removed elements.
// TODO
Examples
// TODO
β Back to top
toCsv
Converts a 2D enumerable to a comma-separated values (CSV) string.
namespace JonasSchubert.Snippets.Enumerable
{
public static partial class Enumerable
{
public static string ToCsv<T>(this IEnumerable<IEnumerable<T>> enumerable, string delimiter = ",")
{
if (enumerable == null)
{
throw new ArgumentNullException(nameof(enumerable));
}
return string.Join("\n", enumerable.Select(subEnumerable => string.Join(delimiter, subEnumerable.Select(value => typeof(T).IsNumericType() ? value.ToString().Replace(",", ".") : value.ToString()))));
}
}
}
Examples
new List<List<bool>> { new List<bool> { true, true }, new List<bool> { true, false } }.ToCsv(); # "True,True\nTrue,False"
new double[][] { new double[] { 1.1, 2.2, 3.3 }, new double[] { 4.4, 5.5, 6.6 } }.ToCsv() # "1.1,2.2,3.3\n4.4,5.5,6.6"
new List<List<TestStruct>> { new List<TestStruct> { new TestStruct { Byte = 0 } }, new List<TestStruct> { new TestStruct { Byte = 1 }, new TestStruct { Byte = 2 } } }.ToCsv("-") # "Byte: 0\nByte: 1-Byte: 2"
β Back to top
toHash
Reduces a given Array-like into a value hash (keyed data store).
// TODO
Examples
// TODO
β Back to top
union
Returns every element that exists in any of the two arrays once.
// TODO
Examples
// TODO
β Back to top
unionBy
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
β Back to top
unionWith
Returns every element that exists in any of the two arrays once, using a provided comparator function.
// TODO
Examples
// TODO
β Back to top
uniqueElements
Returns all unique values of an array.
// TODO
Examples
// TODO
β Back to top
uniqueElementsBy
Returns all unique values of an array, based on a provided comparator function.
// TODO
Examples
// TODO
β Back to top
uniqueElementsByRight
Returns all unique values of an array, based on a provided comparator function.
// TODO
Examples
// TODO
β Back to top
uniqueSymmetricDifference
Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.
// TODO
Examples
// TODO
β Back to top
without
Filters out the elements of an array, that have one of the specified values.
// TODO
Examples
// TODO
β Back to top
xProd
Creates a new array out of the two supplied by creating each possible pair from the arrays.
// TODO
Examples
// TODO
β Back to top
β Math
approximatelyEqual
Checks if two numbers are approximately equal to each other.
// TODO
Examples
// TODO
β Back to top
average
Returns the average of two or more numbers.
The method excepts numbers as params and returns the average as a result.
Linq documentation here.
namespace JonasSchubert.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
β Back to top
averageBy
Returns the average of an array, after mapping each element to a value using the provided function.
// TODO
Examples
// TODO
β Back to top
binomialCoefficient
Evaluates the binomial coefficient of two integers n
and k
.
// TODO
Examples
// TODO
β Back to top
degToRads
Converts an angle from degrees to radians.
namespace JonasSchubert.Snippets.Math
{
public static partial class Math
{
public static double DegToRad(this decimal degree) => (double)degree * System.Math.PI / 180.0;
public static double DegToRad(this double degree) => degree * System.Math.PI / 180.0;
public static double DegToRad(this float degree) => degree * System.Math.PI / 180.0;
public static double DegToRad(this int degree) => degree * System.Math.PI / 180.0;
public static double DegToRad(this uint degree) => degree * System.Math.PI / 180.0;
}
}
Examples
270.0.DegToRad(); # ~ 4.71
-90u.DegToRad(); # ~ 1.57
720.DegToRad(); # ~ 12.57
β Back to top
digitize
Converts a number to an array of digits.
// TODO
Examples
// TODO
β Back to top
distance
Returns the distance between two points.
// TODO
Examples
// TODO
β Back to top
factorial
Calculates the factorial of a number.
namespace JonasSchubert.Snippets.Math
{
public static partial class Math
{
public static uint Factorial(uint number)
{
var result = 1u;
for (var index = number; index > 0; index--)
{
result *= index;
}
return result;
}
}
}
Examples
Math.Factorial(0); # 1
Math.Factorial(3); # 6
Math.Factorial(6); # 720
β Back to top
fibonacci
Generates an list, containing the Fibonacci sequence, up until the nth term.
namespace JonasSchubert.Snippets.Math
{
public static partial class Math
{
public static List<int> Fibonaci(int length)
{
var list = new List<int>();
for (var index = 0; index < length; index++)
{
list.Add(index <= 1 ? index : list[index - 1] + list[index - 2]);
}
return list;
}
}
}
Examples
Math.Fibonaci(2); # new List<int>() { 0, 1 }
Math.Fibonaci(7); # new List<int>() { 0, 1, 1, 2, 3, 5, 8 }
β Back to top
gcd
Calculates the greatest common divisor between two or more numbers/arrays.
// TODO
Examples
// TODO
β Back to top
geometricProgression
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
β Back to top
inRange
Checks if the given number falls within the given range.
// TODO
Examples
// TODO
β Back to top
isDivisibleBy
Checks if the a number is divisible by another number.
namespace JonasSchubert.Snippets.Math
{
public static partial class Math
{
public static bool IsDivisibleBy(this decimal value, decimal divider) => divider == 0 ? throw new DivideByZeroException() : value % divider == 0;
public static bool IsDivisibleBy(this double value, double divider) => divider == 0 ? throw new DivideByZeroException() : value % divider == 0;
public static bool IsDivisibleBy(this float value, float divider) => divider == 0 ? throw new DivideByZeroException() : value % divider == 0;
public static bool IsDivisibleBy(this int value, int divider) => divider == 0 ? throw new DivideByZeroException() : value % divider == 0;
public static bool IsDivisibleBy(this uint value, uint divider) => divider == 0 ? throw new DivideByZeroException() : value % divider == 0;
}
}
Examples
1.IsDivisibleBy(2); # true
-2.0.IsDivisibleBy(2.0); # true
1.0f.IsDivisibleBy(2.0f); # false
2u.IsDivisibleBy(2u); # true
β Back to top
isEven
Returns true
if the given number is even, false
otherwise.
namespace JonasSchubert.Snippets.Math
{
public static partial class Math
{
public static bool IsEven(this decimal value) => value % 2 == 0;
public static bool IsEven(this double value) => value % 2 == 0;
public static bool IsEven(this float value) => value % 2 == 0;
public static bool IsEven(this int value) => value % 2 == 0;
public static bool IsEven(this uint value) => value % 2 == 0;
}
}
Examples
0.IsEven(); # true
1u.IsEven(); # false
-2.0.IsEven(); # true
β Back to top
isPrime
Checks if the provided integer is a prime number.
// TODO
Examples
// TODO
β Back to top
isOdd
Returns true
if the given number is odd, false
otherwise.
namespace JonasSchubert.Snippets.Math
{
public static partial class Math
{
public static bool IsOdd(this decimal value) => value % 2 == 1;
public static bool IsOdd(this double value) => value % 2 == 1;
public static bool IsOdd(this float value) => value % 2 == 1;
public static bool IsOdd(this int value) => value % 2 == 1;
public static bool IsOdd(this uint value) => value % 2 == 1;
}
}
Examples
0.IsOdd(); # false
1u.IsOdd(); # true
-2.0.IsOdd(); # false
β Back to top
lcm
Returns the least common multiple of two or more numbers.
// TODO
Examples
// TODO
β Back to top
luhnCheck
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
β Back to top
max
Returns the maximum value from the provided enumerable.
// TODO
Examples
// TODO
β Back to top
median
Returns the median of an array of numbers.
// TODO
Examples
// TODO
β Back to top
min
Returns the minimum value from the provided enumerable.
// TODO
Examples
// TODO
β Back to top
primes
Generates primes up to a given number, using the Sieve of Eratosthenes.
// TODO
Examples
// TODO
β Back to top
radToDeg
Converts an angle from radians to degrees.
namespace JonasSchubert.Snippets.Math
{
public static partial class Math
{
public static double RadToDeg(this decimal radians) => (double)radians * 180.0 / System.Math.PI;
public static double RadToDeg(this double radians) => radians * 180.0 / System.Math.PI;
public static double RadToDeg(this float radians) => radians * 180.0 / System.Math.PI;
public static double RadToDeg(this int radians) => radians * 180.0 / System.Math.PI;
public static double RadToDeg(this uint radians) => radians * 180.0 / System.Math.PI;
}
}
Examples
(System.Math.PI / 2).RadToDeg() # 90
(System.Math.PI * -2).RadToDeg() # -360
β Back to top
randomIntArrayInRange
Returns an array of n random integers in the specified range.
// TODO
Examples
// TODO
β Back to top
randomIntegerInRange
Returns a random integer in the specified range.
// TODO
Examples
// TODO
β Back to top
randomNumberInRange
Returns a random number in the specified range.
// TODO
Examples
// TODO
β Back to top
round
Rounds a number to a specified amount of digits.
// TODO
Examples
// TODO
β Back to top
sdbm
Hashes the input string into a whole number.
// TODO
Examples
// TODO
β Back to top
standardDeviation
Returns the standard deviation of an array of numbers.
// TODO
Examples
// TODO
β Back to top
sum
Returns the sum of two or more numbers/arrays.
// TODO
Examples
// TODO
β Back to top
sumBy
Returns the sum of an array, after mapping each element to a value using the provided function.
// TODO
Examples
// TODO
β Back to top
ποΈ Method
hz
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.
namespace JonasSchubert.Snippets.Method
{
public static partial class Method
{
public static long Hz(
Action action,
uint iterations = 100000)
{
var watch = Stopwatch.StartNew();
for (var iteration = 0; iteration < iterations; iteration++)
{
action.Invoke();
}
watch.Stop();
return watch.ElapsedMilliseconds > 0
? (iterations * 1000) / watch.ElapsedMilliseconds
: long.MaxValue;
}
...
}
}
Examples
# will return time depending on your PC power
int randomInt() => new Random().Next(0, 1000000);
Method.Hz(randomInt);
char[] charArrayFunc(string test) => test.ToCharArray().Select(x => (char)(x * 2)).Where(x => x > 0).ToArray();
Method.Hz(charArrayFunc);
β Back to top
times
Iterates over a callback n
times
namespace JonasSchubert.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
β Back to top
π String
byteSize
Returns the length of a string in bytes.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static int ByteSize(this string input) => System.Text.Encoding.Default.GetByteCount(input);
public static int ByteSizeAscii(this string input) => System.Text.Encoding.ASCII.GetByteCount(input);
public static int ByteSizeBigEndianUnicode(this string input) => System.Text.Encoding.BigEndianUnicode.GetByteCount(input);
public static int ByteSizeUnicode(this string input) => System.Text.Encoding.Unicode.GetByteCount(input);
public static int ByteSizeUtf7(this string input) => System.Text.Encoding.UTF7.GetByteCount(input);
public static int ByteSizeUtf8(this string input) => System.Text.Encoding.UTF8.GetByteCount(input);
public static int ByteSizeUtf32(this string input) => System.Text.Encoding.UTF32.GetByteCount(input);
}
}
Examples
// TODO
β Back to top
countVowels
Returns number of vowels in provided string.
"".ByteSize(); # 0
"Hello World".ByteSize(); # 11
"Hello World".ByteSizeUnicode(); # 22
"Hello World".ByteSizeUtf32(); # 44
"This is 30 seconds of C.".ByteSizeBigEndianUnicode(); # 48
Examples
// TODO
β Back to top
csvToArray
Converts a comma-separated values (CSV) string to a 2D array.
// TODO
Examples
// TODO
β Back to top
csvToJson
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
β Back to top
endsWithRegex
Check if a string ends with a given substring using a regex.
The method excepts the string to test and a substring to test against.
Most other checks are already integrated.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static bool EndsWithRegex(this string input, string substring) => new Regex($"{substring}$").IsMatch(input);
}
}
Examples
"Hello World".EndsWithRegex(@"[dolrwDOLRW]{5}$") # true
"Hello World, this is it".EndsWithRegex(@"[dolrwDOLRW]{5}$") # false
β Back to top
fromCamelCase
Converts a string from camelcase. Makes all words lowercase and combines them using a provided separator (default is one whitespace). Of the param isSentence == true, the first letter of the sentence will be uppercase and a dot will be added at the end (default is true).
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string FromCamelCase(this string input, string separator = " ", bool isSentence = true)
{
var value = string
.Join(separator, Regex.Matches(input, @"/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g"))
.ToLower();
return isSentence ? $"{char.ToUpperInvariant(value[0])}{value.Substring(1)}." : value;
}
}
}
Examples
"someDatabaseFieldName".FromCamelCase(); # "Some database field name."
"someLabelThatNeedsToBeCamelized".FromCamelCase("-", false); # "some-label-that-needs-to-be-camelized"
"someJavascriptProperty".FromCamelCase("_", false); # "some_javascript_property"
β Back to top
isAnagramOf
Checks if a string is an anagram of another string (case-insensitive).
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static bool IsAnagramOf(this string input, string compare) => input.TransformToCompare() == compare.TransformToCompare();
private static string TransformToCompare(this string input) => string.Join(string.Empty, input.ToLower().OrderBy(x => x));
}
}
Examples
"iceman".IsAnagramOf("cinema"); # true
"icemAn".IsAnagramOf("cinema"; # true
"icem an".IsAnagramOf("cinema"; # false
"ic.EMan".IsAnagramOf("cinema"; # false
"icman".IsAnagramOf("cinema"; # false
β Back to top
isLower
Checks if a string is lower case.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static bool IsLower(this string input) => input == input.ToLower();
}
}
Examples
"abc".IsLower(); # true
"a3@$".IsLower(); # true
"Ab4".IsLower(); # false
β Back to top
isPalindrome
Returns true
if the given string is a palindrome, false
otherwise.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static bool IsPalindrome(this string input) => input.ToLower() == string.Join(string.Empty, input.ToCharArray().Reverse()).ToLower();
}
}
Examples
"tacocat".IsPalindrome(); # true
"tAcocat".IsPalindrome(); # true
"tacoca".IsPalindrome(); # false
β Back to top
isUpper
Checks if a string is upper case.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static bool IsUpper(this string input) => input == input.ToUpper();
}
}
Examples
"ABC".IsUpper(); # true
"A3@$".IsUpper(); # true
"aB4".IsUpper(); # false
β Back to top
mask
Replaces all but the last length
of characters with the specified mask
character.
Omit the second argument, length
, to keep a default of 4
characters unmasked.
If length
is negative, the unmasked characters will be at the start of the string.
Omit the third argument, mask
, to use a default character of '*'
for the mask.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string Mask(this string input, int length = 4, char mask = '*') =>
length >= input.Length
? new string(mask, input.Length)
: length >= 0
? input.Remove(0, input.Length - length).Insert(0, new string(mask, input.Length - length))
: -length >= input.Length
? input
: input.Remove(-length, input.Length + length).Insert(-length, new string(mask, input.Length + length));
}
}
Examples
"1234567890".Mask(); # "******7890"
"1234567890".Mask(3); # "*******890"
"1234567890".Mask(0); # "**********"
"1234567890".Mask(-4); # "1234******"
"1234567890".Mask(20, '-'); # "----------"
"1234567890".Mask(-20, '-'); # "1234567890"
β Back to top
pad
Pads a string on both sides with the specified character, if it's shorter than the specified length.
Use PadLeft()
and PadRight()
to pad both sides of the given string.
Omit the third argument, char
, to use the whitespace character as the default padding character.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string Pad(this string input, int length, char pad = ' ') => input.PadLeft((input.Length + length) / 2, pad).PadRight(length, pad);
}
}
Examples
"Hello World.".Pad(20); # " Hello World. "
"Hello World.".Pad(5, '-'); # "Hello World."
"Dog".Pad(8, ' '); # " Dog "
"42".Pad(6, '0'); # "004200"
β Back to top
removeNonAscii
Removes non-printable ASCII characters. Use a regular expression to remove non-printable ASCII characters.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string RemoveNonAscii(this string input) => Regex.Replace(input, "[^\x20-\x7E]", "");
}
}
Examples
"Γ€ΓΓ§ΓΓ©ΓΓͺlorem ipsumΓΆΓΓΓΎΓΊΓ".RemoveNonAscii(); # "lorem ipsum"
β Back to top
reverse
Reverses a string.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string Reverse(this string input) => string.Join(string.Empty, input.ToCharArray().Reverse());
}
}
Examples
"My name is Jonas Schubert".Reverse(); # "trebuhcS sanoJ si eman yM"
"!This is, maybe not, but important...".Reverse(); # "...tnatropmi tub ,ton ebyam ,si sihT!"
β Back to top
splitLines
Splits a multiline string into an array of lines.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string[] SplitLines(this string input) => Regex.Split(input, "\r?\n");
}
}
Examples
"This\nis a\nmultiline\nstring.\n".SplitLines(); # new string[] { "This", "is a", "multiline", "string.", "" }
β Back to top
startsWithRegex
Check if a string starts with a given substring using a regex.
The method excepts the string to test and a substring to test against.
Most other checks are already integrated.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static bool StartsWithRegex(this string input, string substring) => new Regex($"^{substring}").IsMatch(input);
}
}
Examples
"Hello World".StartsWithRegex(@"[ehloEHLO]{5}$") # true
"Well, hello World".StartsWithRegex(@"[ehloEHLO]{5}$") # false
β Back to top
stripHtmlTags
Removes HTML/XML tags from string. Use a regular expression to remove HTML/XML tags from a string.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string StripHtmlTags(this string input) => Regex.Replace(input, "<[^>]*>", "");
}
}
Examples
"<p><em>lorem</em> <strong>ipsum</strong></p>".StripHtmlTags(); # "lorem ipsum"
"<div><br/>Hello <br />World</div>".StripHtmlTags(); # "Hello World"
β Back to top
toCamelCase
Converts a string to camelcase.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string ToCamelCase(this string input)
{
var value = string.Join(string.Empty, Regex.Matches(input, @"/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g")
.Select(x => $"{x.Value.First().ToString().ToUpper()}{x.Value.Substring(1).ToLower()}"));
return char.ToLowerInvariant(value[0]) + value.Substring(1);
}
}
}
Examples
"some_database_field_name".ToCamelCase(); # "someDatabaseFieldName"
"Some label that needs to be camelized".ToCamelCase(); # "someLabelThatNeedsToBeCamelized"
"some-javascript-property".ToCamelCase(); # "someJavascriptProperty"
"some-mixed_string with spaces_underscores-and-hyphens".ToCamelCase(); # "someMixedStringWithSpacesUnderscoresAndHyphens"
β Back to top
toKebabCase
Converts a string to kebab case.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string ToKebabCase(this string input) =>
string.Join("-", Regex.Matches(input, @"/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g").Select(x => x.Value.ToLower()));
}
}
Examples
"camelCase".ToKebabCase(); # "camel-case"
"some text".ToKebabCase(); # "some-text"
"some-mixed_string With spaces_underscores-and-hyphens".ToKebabCase(); # "some-mixed-string-with-spaces-underscores-and-hyphens"
"AllThe-small Things".ToKebabCase(); # "all-the-small-things"
"IAmListeningToFmWhileLoadingDifferentUrlOnMyBrowserAndAlsoEditingXmlAndHtml".ToKebabCase(); # "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"
β Back to top
toSnakeCase
Converts a string to snake case.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string ToSnakeCase(this string input) =>
string.Join("_", Regex.Matches(input, @"/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g").Select(x => x.Value.ToLower()));
}
}
Examples
"camelCase".ToSnakeCase(); # "camel_case"
"some text".ToSnakeCase(); # "some_text"
"some-mixed_string With spaces_underscores-and-hyphens".ToSnakeCase(); # "some_mixed_string_with_spaces_underscores_and_hyphens"
"AllThe-small Things".ToSnakeCase(); # "all_the_small_things"
"IAmListeningToFmWhileLoadingDifferentUrlOnMyBrowserAndAlsoEditingXmlAndHtml".ToSnakeCase(); # "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_xml_and_html"
β Back to top
toTitleCase
Converts a string to title case.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string ToTitleCase(this string input) =>
string.Join(" ", Regex.Matches(input, @"/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g")
.Select(x => $"{x.Value.First().ToString().ToUpper()}{x.Value.Substring(1).ToLower()}"));
}
}
Examples
"some_database_field_name".ToTitleCase(); # "Some Database Field Name"
"Some label that needs to be title-cased".ToTitleCase(); # "Some Label That Needs To Be Title Cased"
"some-package-name".ToTitleCase(); # "Some Package Name"
"some-mixed_string with spaces_underscores-and-hyphens".ToTitleCase(); # "Some Mixed String With Spaces Underscores And Hyphens"
β Back to top
truncate
Truncates a string up to a specified length.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static string Truncate(this string input, int maxLength) =>
input.Length > maxLength ? $"{input.Substring(0, maxLength > 3 ? maxLength - 3 : maxLength)}..." : input;
}
}
Examples
"Hello World".Truncate(4); # "H..."
"Hello World".Truncate(12); # "Hello World"
β Back to top
words
Converts a given string into a list of words.
namespace JonasSchubert.Snippets.String
{
public static partial class String
{
public static List<string> Words(this string input, string pattern = @"\w+[^\s]*\w+|\w") =>
Regex.Matches(input, pattern).Select(x => x.Value).ToList();
}
}
Examples
"Hello World".Words(); # new List<string> { "Hello", "World" }
"Hello".Words(); # new List<string> { "Hello" }
" ".Words(); # new List<string>()
β Back to top
ποΈ Type
isNumericType
Checks if the provided type is of a numeric type.
namespace JonasSchubert.Snippets.Type2
{
public static partial class Type2
{
public static bool IsNumericType(this Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
default:
return false;
}
}
}
}
Examples
typeof(sbyte).IsNumericType(); # true
typeof(short).IsNumericType(); # true
typeof(float).IsNumericType(); # true
typeof(string).IsNumericType(); # false
typeof(int[]).IsNumericType(); # false
β Back to top
π§ Utility
extendHex
Extends a 3-digit color code to a 6-digit color code.
namespace JonasSchubert.Snippets.Utility
{
public static partial class Utility
{
public static string ExtendHex(this string hex) =>
$"{string.Join("", (hex.StartsWith('#') ? hex : $"#{hex}").Select(x => x == '#' ? $"{x}" : $"{x}{x}"))}";
}
}
Examples
"#03f".ExtendHex(); # "#0033ff"
"05a".ExtendHex(); # "#0055aa"
β Back to top
hexToRgb
Converts a color code to a rgb()
or rgba()
string if alpha value is provided.
namespace JonasSchubert.Snippets.Utility
{
public static partial class Utility
{
public static string HexToRgb(string value)
{
value = value.Replace("#", "");
var hasAlpha = value.Length == 8;
value = value.Length == 3 ? string.Join("", value.Select(x => $"{x}{x}")) : value;
var valueAsInt = int.Parse(value, NumberStyles.HexNumber);
var red = valueAsInt >> (hasAlpha ? 24 : 16);
var green = (valueAsInt & (hasAlpha ? 0x00ff0000 : 0x00ff00)) >> (hasAlpha ? 16 : 8);
var blue = (valueAsInt & (hasAlpha ? 0x0000ff00 : 0x0000ff)) >> (hasAlpha ? 8 : 0);
var alpha = hasAlpha ? $"{ valueAsInt & 0x000000ff}" : null;
return $"rgb{(hasAlpha ? "a" : "")}({red}, {green}, {blue}{(hasAlpha ? $", {alpha}" : "")})";
}
}
}
Examples
Utility.HexToRgb("#fff"); # "rgb(255, 255, 255)"
Utility.HexToRgb("#27ae60"); # "rgb(39, 174, 96)"
Utility.HexToRgb("#27ae60ff"); # "rgba(39, 174, 96, 255)"
β Back to top
prettyBytes
Converts a number in bytes to a human-readable string.
namespace JonasSchubert.Snippets.Utility
{
public static partial class Utility
{
public static string PrettyBytes(ulong bytes)
{
var units = new string[] { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
var stringArray = units
.Select((unit, index) =>
Math.Floor(bytes / Math.Pow(1e3, index) % 1e3) > 0
? $"{Math.Floor(bytes / Math.Pow(1e3, index) % 1e3)} {unit}{(Math.Floor(bytes / Math.Pow(1e3, index) % 1e3) > 1 ? "s" : string.Empty)}"
: string.Empty)
.Where(x => !string.IsNullOrEmpty(x))
.Reverse()
.ToArray();
return stringArray.Length > 0
? string.Join(", ", stringArray)
: "0 B";
}
}
}
Examples
Utility.PrettyBytes(0ul); # "0 B"
Utility.PrettyBytes(1001ul); # "1 KB, 1 B"
Utility.PrettyBytes(20000000000000000ul); # "20 PBs"
Utility.PrettyBytes(1001001001ul); # "1 GB, 1 MB, 1 KB, 1 B"
β Back to top
randomHexColor
Generates a random hexadecimal color.
namespace JonasSchubert.Snippets.Utility
{
public static partial class Utility
{
public static string RandomHexColor() =>
$"#{(new Random().Next() * 0xFFFFFF * 1000000).ToString("X").PadLeft(6, '0').Substring(0, 6)}";
}
}
Examples
Utility.RandomHexColor(); # "#01A5FF" (e.g.)
β Back to top
rgbToHex
Converts the values of RGB components to a color code.
namespace JonasSchubert.Snippets.Utility
{
public static partial class Utility
{
public static string RgbToHex(int red, int green, int blue) =>
$"#{((red << 16) + (green << 8) + blue).ToString("X").PadLeft(6, '0')}";
}
}
Examples
Utility.RgbToHex(0, 0, 0); # "#000000"
Utility.RgbToHex(1, 165, 255); # "#01A5FF"
Utility.RgbToHex(255, 255, 255); # "#FFFFFF"
β Back to top
timeTaken
Measures the time taken by a function to execute.
Stopwatch documentation here.
namespace JonasSchubert.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
β Back to top
yesNo
Returns true
if the string is y
/yes
or false
if the string is n
/no
.
namespace JonasSchubert.Snippets.Utility
{
public static partial class Utility
{
public static bool YesNo(this string test, bool defaultVal = false) =>
new Regex(@"^(y|yes)$", RegexOptions.IgnoreCase).IsMatch(test)
? true
: new Regex(@"^(n|no)$", RegexOptions.IgnoreCase).IsMatch(test)
? false
: defaultVal;
}
}
Examples
var empty = "".YesNo(); # false
var yes = "yes".YesNo(); # true
var y = "y".YesNo(); # true
var NO = "NO".YesNo(); # false
var nO = "nO".YesNo(); # false
β Back to top
Contribute
You're always welcome to contribute to this project. Please read the contribution guide.
Contributors
Jonas Schubert | Denis Biondic |
License
30 Seconds of C# is distributed under the MIT license. See LICENSE for details.
MIT License
Copyright (c) 2018 - 2020 JonasSchubert
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.