All
- title: All
- tags: array,list,lambda,overload,intermediate
Returns true
if the provided predicate function returns true
for all elements in a collection, false
otherwise.
- Use
IEnumerable.ToArray()
,Array.TrueForAll()
to test if all elements in the collection returntrue
based on the predicate function,match
. - Omit the predicate function,
match
, to use the overload that checks if each value is different fromnull
by default.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static bool All<T>(IEnumerable<T> data, Predicate<T> match)
{
return Array.TrueForAll(data.ToArray(), match);
}
public static bool All<T>(IEnumerable<T> data)
{
return Array.TrueForAll(data.ToArray(), val => val != null);
}
}
int[] nums = { 4, 2, 3 };
_30s.All(nums, x => x > 1); // true
_30s.All(nums); // true
AverageBy
- title: AverageBy
- tags: math,list,array,lambda,intermediate
Returns the average of a collection, after mapping each element to a value using the provided function.
- Use
IEnumerable.Select()
to map each element to the value returned by the provided selector function,fn
. - Use
IEnumerable.Average()
to get the average of the resulting values.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static double AverageBy<T>(IEnumerable<T> values, Func<T,int> fn)
{
return values.Select(fn).Average();
}
}
var p = new [] {
new { a = 3, b = 2},
new { a = 2, b = 1}
};
_30s.AverageBy(p, v => v.a); // 2.5
_30s.AverageBy(p, v => v.b); // 1.5
Bifurcate
- title: Bifurcate
- tags: array,list,intermediate
Splits values into two groups.
If an element in filter
is true
, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
- Use
IEnumerable.Where()
to separate values into two groups and assign them to the two passedout
arrays.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static void Bifurcate<T>(IEnumerable<T> items, IList<bool> filter, out T[] filteredTrue, out T[] filteredFalse)
{
filteredTrue = items.Where((val, i) => filter[i] == true).ToArray();
filteredFalse = items.Where((val, i) => filter[i] == false).ToArray();
}
}
int[] nums = {1, 2, 3, 4};
bool[] filter = {true, true, false, true};
int[] n1;
int[] n2;
_30s.Bifurcate(nums, filter, out n1, out n2); // // n1 = {1, 2, 4}, n2 = {3}
BifurcateBy
- title: BifurcateBy
- tags: array,list,lambda,advanced
Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
- Use
IEnumerable.Where()
to separate values into two groups and assign them to the two passedout
arrays.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static void BifurcateBy<T>(IEnumerable<T> items, Predicate<T> filter, out T[] filteredTrue, out T[] filteredFalse)
{
filteredTrue = items.Where(i => filter(i) == true).ToArray();
filteredFalse = items.Where(i => filter(i) == false).ToArray();
}
}
int[] nums = {1, 2, 3, 4};
int[] n1;
int[] n2;
_30s.BifurcateBy(nums, x => x % 2 == 0, out n1, out n2); // n1 = {2, 4}, n2 = {1, 3}
ByteArrayToHex
- title: ByteArrayToHex
- tags: array,utility,beginner
Converts a byte
array to its hexadecimal string representation.
- Use
BitConverter.ToString()
to convert thebyte
array to a string. - Use
string.Replace()
to remove dashes in the produced string.
public static partial class _30s
{
public static string ByteArrayToHex(byte[] bytes)
{
return BitConverter.ToString(bytes).Replace("-", "");
}
}
byte[] data = { 241, 89, 54 };
_30s.ByteArrayToHex(data); // "F15936"
Capitalize
- title: Capitalize
- tags: string,beginner
Capitalizes the first letter of a string.
- Use
string.ToCharArray()
to convert the string to an array ofchar
,chars
. - Use
char.ToUpper(chars[0])
to capitalize the first letter. - Finally, return a
new string()
from thechars
array.
public static partial class _30s
{
public static string Capitalize(string str)
{
char[] chars = str.ToCharArray();
chars[0] = char.ToUpper(chars[0]);
return new string(chars);
}
}
string s = "fooBar";
_30s.Capitalize(s); // "FooBar"
Chunk
- title: Chunk
- tags: array,list,lambda,advanced
Chunks a collection into smaller lists of a specified size.
- Use
IEnumerable.Select()
to convert the given list to index-value pairs. - Use
IEnumerable.GroupBy()
to split elements into groups based on their index. - Use
IEnumerable.Select()
a second time to map each group's elements to their values andIEnumerable.ToList()
to convert the result to a list. - Finally, use
IEnumerable.ToList()
on the result to convert everything to a list and return it. - If the original list can't be split evenly, the final chunk will contain the remaining elements.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static List<List<T>> Chunk<T>(IEnumerable<T> data, int size)
{
return data
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / size)
.Select(x => x.Select(v => v.Value).ToList())
.ToList();
}
}
List<int> nums = new List<int> { 1, 2, 3, 4, 5 };
_30s.Chunk(nums, 2); // { {1, 2}, {3, 4}, {5} }
CompactWhitespace
- title: CompactWhitespace
- tags: string,regex,intermediate
Returns a string with whitespaces compacted.
- Use
Regex.Replace()
with a regular expression to replace all occurences of 2 or more subsequent whitespace characters with a single space.
using System.Text.RegularExpressions;
public static partial class _30s
{
public static string CompactWhitespace(string str)
{
return Regex.Replace(str, @"\s{2,}", " ");
}
}
string s = "Lorem ipsum\n dolor sit amet";
_30s.CompactWhitespace(s); // "Lorem ipsum dolor sit amet"
CountBy
- title: CountBy
- tags: array,list,lambda,intermediate
Groups the elements of a collection based on the given function and returns the count of elements in each group.
- Use
IEnumerable.GroupBy()
to create groups for each distinct value in the collection, after applying the provided function. - Use
IEnumerable.ToDictionary()
to convert the result of the previous operation to aDictionary
.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static Dictionary<R,int> CountBy<T,R>(IEnumerable<T> values, Func<T,R> map)
{
return values
.GroupBy(map)
.ToDictionary(v => v.Key, v => v.Count());
}
}
var p = new[] {
new { a = 3, b = 2},
new { a = 2, b = 1}
};
_30s.CountBy(p, x => x.a); // { [3, 1], [2, 1] }
CountOccurences
- title: CountOccurences
- tags: array,list,intermediate
Counts the occurences of a value in a collection.
- Use
IEnumerable.Count()
in combination withEqualityComparer<T>.Default.Equals()
to compare each value in theIEnumerable
withel
.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static int CountOccurences<T>(IEnumerable<T> obj, T el)
{
return obj.Count(f => EqualityComparer<T>.Default.Equals(f, el));
}
}
string s = "fooBar";
List<int> nums = new List<int> { 1, 2, 3, 3, 3, 4, 5, 6 };
_30s.CountOccurences(s,'o'); // 2
_30s.CountOccurences(nums,3); // 3
DayOfTheWeek
- title: DayOfTheWeek
- tags: date,utility,beginner
Returns the string representation of the weekday for the given DateTime
.
- Use
DateTime.ToString()
with an appropriate format modifier to return the day of the week.
public static partial class _30s
{
public static string DayOfTheWeek(DateTime date)
{
return date.ToString("dddd");
}
}
_30s.DayOfTheWeek(new DateTime(2020, 1, 15)); // "Wednesday"
Decapitalize
- title: Decapitalize
- tags: string,beginner
Decapitalizes the first letter of a string.
- Use
string.ToCharArray()
to convert the string to an array ofchar
,chars
. - Use
char.ToLower(chars[0])
to decapitalize the first letter. - Finally, return a
new string()
from thechars
array.
public static partial class _30s
{
public static string Decapitalize(string str)
{
char[] chars = str.ToCharArray();
chars[0] = char.ToLower(chars[0]);
return new string(chars);
}
}
string s = "FooBar";
_30s.Decapitalize(s); // "fooBar"
Difference
- title: Difference
- tags: array,list,beginner
Returns the difference betweend two collections.
- Use
IEnumerable.Except()
to only return elements in the second enumerable object and not the first one.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<T> Difference<T>(IEnumerable<T> a, IEnumerable<T> b)
{
return a.Except(b);
}
}
int[] a = { 1, 2, 3, 5 };
int[] b = { 1, 2, 4 };
_30s.Difference(a, b); // { 3, 5 }
DifferenceBy
- title: DifferenceBy
- tags: array,list,lambda,advanced
Returns the difference between two collections, after applying the provided function to each element of both.
- Use
IEnumerable.Select()
to map each element of either collection to the desired type. - Use
IEnumerable.Except()
to only return elements in the second enumerable object and not the first one.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<R> DifferenceBy<T,R>(IEnumerable<T> a, IEnumerable<T> b, Func<T,R> map)
{
return a.Select(map).Except(b.Select(map));
}
}
var p = new[] {
new { a = 3, b = 2},
new { a = 2, b = 1}
};
var q = new[] {
new { a = 6, b = 2}
};
_30s.DifferenceBy(p, q, x => x.b); // { 1 }
DistinctValues
- title: DistinctValues
- tags: array,list,beginner
Returns all distinct values in a collection.
- Use
IEnumerable.Distinct()
to get the distinct values in the given collection.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<T> DistinctValues<T>(IEnumerable<T> data)
{
return data.Distinct();
}
}
int[] nums = { 1, 2, 1, 3, 3, 4, 5 };
_30s.DistinctValues(nums); // { 1, 2, 3, 4, 5 }
DuplicateValues
- title: DuplicateValues
- tags: array,list,intermediate
Returns all distinct values in a collection.
- Use
IEnumerable.GroupBy()
to create groups for each distinct value in the enumerable. - Use
IEnumerable.Where()
to create select only the groups with a count greater than1
. - Use
IEnumerable.Select()
to return theKey
property of each group.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<T> DuplicateValues<T>(IEnumerable<T> items)
{
return items
.GroupBy(c => c)
.Where(g => g.Count() > 1)
.Select(i => i.Key);
}
}
int[] arr = {1, 2, 1, 3, 2, 4};
_30s.DuplicateValues(arr); // {1, 2}
Fibonacci
- title: Fibonacci
- tags: math,array,intermediate
Generates an array, containing the Fibonacci sequence, up until the nth term.
- Starting with
0
and1
, loop from2
throughn
adding the sum of the last two numbers and appending to the sequence. - If
n
is less or equal to0
, return a list containing0
.
public static partial class _30s
{
public static int[] Fibonacci(int n)
{
if (n <= 0 ) return new [] { 0 };
int[] fib = new int[n + 1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i ++)
{
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib;
}
}
_30s.Fibonacci(7); // { 0, 1, 1, 2, 3, 5, 8, 13 }
FilterString
- title: FilterString
- tags: string,utility,intermediate
Filter a string's contents to include only alphanumeric and allowed characters.
- Use
string.ToCharArray()
in combination withArray.FindAll()
to check if each character in the string is alphanumeric or contained in thefilter
. - Omit the second argument,
filter
, to only allow alphanumeric characters.
using System.Collections.Generic;
public static partial class _30s
{
public static string FilterString(string s, string filter = "")
{
return new string(
Array.FindAll(s.ToCharArray(), c => char.IsLetterOrDigit(c) || filter.Contains(c))
);
}
}
string s = "@30_seconds_of_code##-$";
_30s.FilterString(s); // "30secondsofcode"
_30s.FilterString(s,"_"); // "30_seconds_of_code"
_30s.FilterString(s,"_@"); // "@30_seconds_of_code"
FindFirstBy
- title: FindFirstBy
- tags: array,list,lambda,intermediate
Returns the first element in a collection that matches the given predicate function, match
.
- Use
IEnumerable.Where()
to filter out all values indata
for whichmatch
returnsfalse
. - Use
IEnumerable.First()
to return only the first matching element.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static T FindFirstBy<T>(IEnumerable<T> data, Predicate<T> match)
{
return data.Where(i => match(i)).First();
}
}
int[] nums = {1, 2, 4, 5, 2, 2, 4};
_30s.FindFirstBy(nums, x => x % 2 == 0); // 2
FindIndexOfAll
- title: FindIndexOfAll
- tags: array,list,lambda,intermediate
Returns all indices in an IList
that match the given predicate function, match
.
- Use
Enumerable.Range()
to iterate over all indices indata
. - Use
IEnumerable.Where()
to filter out all values indata
for whichmatch
returnsfalse
and return only matching indices.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<int> FindIndexOfAll<T>(IList<T> data, Predicate<T> match)
{
return Enumerable
.Range(0, data.Count())
.Where(i => match(data[i]));
}
}
int[] nums = {1, 2, 4, 5, 2, 2, 4};
_30s.FindIndexOfAll(nums, x => x % 2 != 0); // {0, 3}
FindIndexOfFirstBy
- title: FindIndexOfFirstBy
- tags: array,list,lambda,intermediate
Returns the first index in an IList
that matches the given predicate function, match
.
- Use
Enumerable.Range()
to iterate over all indices indata
. - Use
IEnumerable.Where()
to filter out all values indata
for whichmatch
returnsfalse
. - Use
IEnumerable.First()
to return only the first matching index.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static int FindIndexOfFirstBy<T>(IList<T> data, Predicate<T> match)
{
return Enumerable
.Range(0, data.Count())
.Where(i => match(data[i]))
.First();
}
}
int[] nums = {1, 2, 4, 5, 2, 2, 4};
_30s.FindIndexOfFirstBy(nums, x => x % 2 == 0); // 1
FindIndexOfLastBy
- title: FindIndexOfLastBy
- tags: array,list,lambda,intermediate
Returns the last index in an IList
that matches the given predicate function, match
.
- Use
Enumerable.Range()
to iterate over all indices indata
. - Use
IEnumerable.Where()
to filter out all values indata
for whichmatch
returnsfalse
. - Use
IEnumerable.Last()
to return only the last matching index.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static int FindIndexOfLastBy<T>(IList<T> data, Predicate<T> match)
{
return Enumerable
.Range(0, data.Count())
.Where(i => match(data[i]))
.Last();
}
}
int[] nums = {1, 2, 4, 5, 2, 2, 4};
_30s.FindIndexOfLastBy(nums, x => x % 2 == 0); // 6
FindLastBy
- title: FindLastBy
- tags: array,list,lambda,intermediate
Returns the last element in a collection that matches the given predicate function, match
.
- Use
IEnumerable.Where()
to filter out all values indata
for whichmatch
returnsfalse
. - Use
IEnumerable.Last()
to return only the last matching element.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static T FindLastBy<T>(IEnumerable<T> data, Predicate<T> match)
{
return data.Where(i => match(i)).Last();
}
}
int[] nums = {1, 2, 4, 5, 2, 2, 4};
_30s.FindLastBy(nums, x => x % 2 == 0); // 4
FindParityOutliers
- title: FindParityOutliers
- tags: array,list,math,advanced
Given a collection, returns the items that are parity outliers.
- Use
IEnumerable.GroupBy()
to create groups for each parity (0
and1
). - Use
IEnumerable.OrderBy()
in combination withIEnumerable.Count()
to order the two groups in ascending order based on frequency. - Use
IEnumerable.First()
to get the first element and return itsKey
property, which corresponds to the least common parity value. - Finally, use
IEnumerable.Where()
to get all elements with the least common parity value.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<int> FindParityOutliers(IEnumerable<int> items)
{
return items.Where(
i => i % 2 == items
.GroupBy(i => i % 2)
.OrderBy(i => i.Count())
.First()
.Key
);
}
}
int[] nums = {1, 2, 3, 4, 6};
_30s.FindParityOutliers(nums); // {1, 3}
Flatten
- title: Flatten
- tags: array,list,intermediate
Flattens a 2D collection into a single dimension.
- Use
IEnumerable.SelectMany()
to flatten the 2D enumerable object.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<T> Flatten<T>(IEnumerable<IEnumerable<T>> obj)
{
return obj.SelectMany(v => v);
}
}
int[][] x = {
new [] {1, 2, 3},
new [] {4, 5, 6}
};
_30s.Flatten(x); // {1, 2, 3, 4, 5, 6}
FormatDuration
- title: FormatDuration
- tags: date,utility,beginner
Returns the human readable format of the given number of seconds.
- Use
TimeSpan.FromSeconds()
to convert the number ofseconds
to aTimeSpan
object. - Use
TimeSpan.ToString()
with an appropriate format specifier to return a human readable string of the value.
public static partial class _30s
{
public static string FormatDuration(double seconds)
{
return TimeSpan.FromSeconds(seconds).ToString(@"d\.hh\:mm\:ss\.fff");
}
}
_30s.FormatDuration(34325055.574); // 397.06:44:15.574
Frequencies
- title: Frequencies
- tags: array,list,dictionary,intermediate
Returns a Dictionary
with the unique values of a collection as keys and their frequencies as the values.
- Use
IEnumerable.GroupBy()
to create groups for each distinct value in the collection. - Use
IEnumerable.ToDictionary()
to convert the result of the previous operation to aDictionary
.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static Dictionary<T,int> Frequencies<T>(IEnumerable<T> values)
{
return values
.GroupBy(v => v)
.ToDictionary(v => v.Key, v => v.Count());
}
}
char[] c = {'a', 'b', 'a', 'c', 'a', 'a', 'b'};
_30s.Frequencies(c); // { [a, 4], [b, 2], [c, 1] }
GCD
- title: GCD
- tags: math,recursion,overload,intermediate
Calculates the greatest common divisor of the given numbers.
- Define a
GCD()
function for two numbers, which uses recursion. - Base case is when
y
equals0
, which returnsx
. - Otherwise the GCD of
y
and the remainder of the divisionx/y
is returned. - Define an overload that accepts multiple numbers or an array and use
IEnumerable.Aggregate()
to applyGCD()
to them.
using System.Linq;
public static partial class _30s
{
public static int GCD(params int[] nums)
{
return nums.Aggregate(GCD);
}
public static int GCD(int x, int y)
{
return y == 0 ? x : GCD(y, x % y);
}
}
_30s.GCD(8, 36, 28); // 4
GetFirstN
- title: GetFirstN
- tags: array,list,intermediate
Returns the first n
elements in a collection.
- Use
IEnumerable.Count()
to check if the enumerable is non-empty. - Use
IEnumerable.Take(n)
to get the firstn
elements. - If the enumerable object is empty, return the
default()
value for the given enumerable. - Omit the second argument,
n
, to use a default value of1
.
public static partial class _30s
{
public static IEnumerable<T> GetFirstN<T>(IEnumerable<T> list, int n = 1)
{
return list.Count() != 0 ? list.Take(n) : default(IEnumerable<T>);
}
}
List<int> nums = new List<int> { 1, 2, 3, 4, 5 };
_30s.GetFirstN(nums); // { 1 }
_30s.GetFirstN(nums, 3); // { 1, 2, 3 }
GetLastN
- title: GetLastN
- tags: array,list,intermediate
Returns the last n
elements in a collection.
- Use
IEnumerable.Count()
to check if the enumerable is non-empty. - Use
IEnumerable.Skip(list.Count() - n)
to get the lastn
elements. - If the enumerable object is empty, return the
default()
value for the given enumerable. - Omit the second argument,
n
, to use a default value of1
.
public static partial class _30s
{
public static IEnumerable<T> GetLastN<T>(IEnumerable<T> list, int n = 1)
{
return list.Count() != 0 ? list.Skip(list.Count() - n) : default(IEnumerable<T>);
}
}
List<int> nums = new List<int> { 1, 2, 3, 4, 5 };
_30s.GetLastN(nums); // { 5 }
_30s.GetLastN(nums, 3); // { 3, 4, 5 }
GetType
- title: GetType
- tags: utility,type,beginner
Returns the type of the given object.
- Use
typeof()
on the given object's type.
public static partial class _30s
{
public static Type GetType<T>(T obj)
{
return typeof(T);
}
}
string s = "fooBar";
List<string> list = new List<string> { "a", "b", "c" };
_30s.GetType(s); // System.String
_30s.GetType(list); // System.Collections.Generic.List`1[System.String]
HaveSameContents
- title: HaveSameContents
- tags: array,list,dictionary,advanced
Returns true
if two collections contain the same elements regardless of order, false
otherwise.
- Use
IEnumerable.GroupBy()
to create groups for each distinct value in each collection,IEnumerable.ToDictionary()
to convert the result to aDictionary
. - Use
IEnumerable.Union()
andIEnumerable.Distinct()
to find the distinct values from both collections and loop over them using aforeach
loop. - Use
Dictionary.ContainsKey()
to check that each distinct value exists in both collections and compare the count for each one. - Return
false
if any value is not found in either collection or if any count does not match,true
otherwise.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static bool HaveSameContents<T>(IEnumerable<T> a, IEnumerable<T> b)
{
Dictionary<T,int> dA = a.GroupBy(v => v).ToDictionary(v => v.Key, v => v.Count());
Dictionary<T,int> dB = b.GroupBy(v => v).ToDictionary(v => v.Key, v => v.Count());
foreach (T val in a.Union(b).Distinct()) {
if (!dA.ContainsKey(val) || !dB.ContainsKey(val)) return false;
if (dA[val] != dB[val]) return false;
}
return true;
}
}
int[] a = {1, 2, 4};
int[] b = {2, 4, 1};
_30s.HaveSameContents(a, b); // true
Head
- title: Head
- tags: array,list,intermediate
Returns the head of a collection.
- Use
IEnumerable.Count()
to check if the enumerable is non-empty. - Use
IEnumerable.Take(1)
to get the first element,IEnumerable.ToArray()[0]
to convert to array and return the element. - If the enumerable object is empty, return the
default()
value for the given type.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static T Head<T>(IEnumerable<T> list)
{
return list.Count() != 0 ? list.Take(1).ToArray()[0] : default(T);
}
}
List<int> nums = new List<int> { 1, 2, 3, 4, 5 };
List<int> empty = new List<int> { };
char[] chars = {'A','B','C'};
_30s.Head(nums); // 1
_30s.Head(empty); // 0
_30s.Head(chars); // 'A'
HexToByteArray
- title: HexToByteArray
- tags: string,utility,advanced
Converts a hexadecimal string to a byte
array.
- Use
Enumerable.Range()
in combination withstring.Length
to get the indices of the given string in an array. - Use
Enumerable.Where()
to get only the even indices in the previous range. - Use
Enumerable.Select()
in combination withConvert.ToByte()
andstring.Substring()
to convert each byte's hex code to abyte
. - Finally, use
Enumerable.ToArray()
to return abyte[]
.
using System.Linq;
public static partial class _30s
{
public static byte[] HexToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}
_30s.HexToByteArray("F15936"); // { 241, 89, 54 }
IndexOfAll
- title: IndexOfAll
- tags: array,list,intermediate
Returns all indices of n
in an IList
.
- Use
Enumerable.Range()
to iterate over all indices indata
. - Use
Enumerable.Where()
in combination withobject.Equals()
to compare each value indata
ton
and return only matching indices.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<int> IndexOfAll<T>(IList<T> data, T n)
{
return Enumerable
.Range(0, data.Count())
.Where(i => object.Equals(n, data[i]));
}
}
int[] nums = {1, 2, 4, 5, 2, 2, 4};
_30s.IndexOfAll(_30s.IndexOfAll(nums, 2)); // {1, 4, 5}
Initialize2DArray
- title: Initialize2DArray
- tags: array,utility,advanced
Initializes a 2D array of the given width, height and value.
- Use
Enumerable.Repeat()
to repeatvalue
width
times, convert to an array and repeatheight
times using the same method. - Use
IEnumerable.Select()
andIEnumerable.First()
to convert the jagged array to a 2D array.
using System.Linq;
public static partial class _30s
{
public static T[,] Initialize2DArray<T>(int width, int height, T value)
{
return new [] { new T [height, width] }
.Select(_ => new { x = _, y = Enumerable.Repeat(
Enumerable.Repeat(value, width).ToArray(), height
)
.ToArray()
.Select((a, ia) => a.Select((b, ib) => _[ia, ib] = b).Count()).Count() }
)
.Select(_ => _.x)
.First();
}
}
_30s.Initialize2DArray(2, 3, 5); // { {5, 5}, {5, 5}, {5, 5} }
IsA
- title: IsA
- tags: utility,type,beginner
Returns true
if the given object is of the specified type, false
otherwise.
- Use the
is
operator to check ifobj
is of the given type,T
.
public static partial class _30s
{
public static bool IsA<T>(object obj)
{
return obj is T;
}
}
string s = "fooBar";
_30s.IsA<string>(s); // true
_30s.IsA<int>(s); // false
IsContainedIn
- title: IsContainedIn
- tags: array,list,dictionary,advanced
Returns true
if the elements of the first collection are contained in the second one regardless of order, false
otherwise.
- Use
IEnumerable.GroupBy()
to create groups for each distinct value in each collection,IEnumerable.ToDictionary()
to convert the result to aDictionary
. - Use
IEnumerable.Distinct()
to find the distinct values from the first collection and loop over them using aforeach
loop. - Use
Dictionary.ContainsKey()
to check that each distinct value exists in the second collection and compare the count for each one. - Return
false
if any value is not found in the second collection or if any count in it is lower than in the first one,true
otherwise.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static bool IsContainedIn<T>(IEnumerable<T> a, IEnumerable<T> b)
{
Dictionary<T,int> dA = a.GroupBy(v => v).ToDictionary(v => v.Key, v => v.Count());
Dictionary<T,int> dB = b.GroupBy(v => v).ToDictionary(v => v.Key, v => v.Count());
foreach(T val in a.Distinct()) {
if (!dB.ContainsKey(val)) return false;
if (dA[val] > dB[val]) return false;
}
return true;
}
}
int[] a = {1, 4};
int[] b = {2, 4, 1};
_30s.IsContainedIn(a, b); // true
IsDivisible
- title: IsDivisible
- tags: math,beginner
Checks if the first numeric argument is divisible by the second one.
- Use the modulo operator (
%
) to check if the remainder is equal to0
.
public static partial class _30s
{
public static bool IsDivisible(long dividend, long divisor)
{
return dividend % divisor == 0;
}
}
_30s.IsDivisible(6, 3); // true
IsDouble
- title: IsDouble
- tags: math,type,intermediate
Returns true
if the given string can be parsed into a double, false
otherwise.
- Return the result of calling
Double.TryParse()
withNymberStyles.Float
for the givennum
string.
using System.Globalization;
public static partial class _30s
{
public static bool IsDouble(string num)
{
Double _ = 0.0;
return Double.TryParse(num, NumberStyles.Float, NumberFormatInfo.CurrentInfo, out _);
}
}
_30s.IsDouble("2"); // true
_30s.IsDouble("hi"); // false
IsEven
- title: IsEven
- tags: math,beginner
Returns true
if the given number is even, false
otherwise.
- Check whether a number is odd or even using the modulo (
%
) operator. - Return
true
if the number is even,false
if the number is odd.
public static partial class _30s
{
public static bool IsEven(int n)
{
return n % 2 == 0;
}
}
_30s.IsEven(2); // true
_30s.IsEven(3); // false
IsInteger
- title: IsInteger
- tags: math,type,intermediate
Returns true
if the given string can be parsed into an integer, false
otherwise.
- Return the result of calling
Double.TryParse()
withNymberStyles.Integer
for the givennum
string. - Use
Double.TryParse()
to allow handling of values larger thanInt64
.
using System.Globalization;
public static partial class _30s
{
public static bool IsInteger(string num)
{
Double _ = 0.0;
return Double.TryParse(num, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out _);
}
}
_30s.IsInteger("2"); // true
_30s.IsInteger("3.1"); // false
IsLower
- title: IsLower
- tags: string,beginner
Checks if a string is lower case.
- Convert the given string to lower case, using
string.ToLower()
and compare it to the original.
public static partial class _30s
{
public static bool IsLower(string str)
{
return str.ToLower() == str;
}
}
string s1 = "abc";
string s2 = "cDe";
_30s.IsLower(s1); // true
_30s.IsLower(s2); // false
IsNotA
- title: IsNotA
- tags: utility,type,beginner
Returns true
if the given object is not of the specified type, false
otherwise.
- Use the
is
operator to check ifobj
is not of the given type,T
.
public static partial class _30s
{
public static bool IsNotA<T>(object obj)
{
return !(obj is T);
}
}
string s = "fooBar";
_30s.IsNotA<string>(s); // false
_30s.IsNotA<int>(s); // true
IsOdd
- title: IsOdd
- tags: math,beginner
Returns true
if the given number is odd, false
otherwise.
- Check whether a number is odd or even using the modulo (
%
) operator. - Return
true
if the number is odd,false
if the number is even.
public static partial class _30s
{
public static bool IsOdd(int n)
{
return n % 2 != 0;
}
}
_30s.IsOdd(3); // true
_30s.IsOdd(4); // false
IsPowerOfTwo
- title: IsPowerOfTwo
- tags: math,intermediate
Returns true
if the given number is a power of 2
, false
otherwise.
- Use the bitwise binary AND operator (
&
) to determine ifn
is a power of2
. - Additionally, check that
n
is different from0
.
public static partial class _30s
{
public static bool IsPowerOfTwo(ulong n)
{
return (n != 0) && ((n & (n - 1)) == 0);
}
}
_30s.IsPowerOfTwo(0); // false
_30s.IsPowerOfTwo(1); // true
_30s.IsPowerOfTwo(8); // true
IsUpper
- title: IsUpper
- tags: string,beginner
Checks if a string is upper case.
- Convert the given string to upper case, using
string.ToUpper()
and compare it to the original.
public static partial class _30s
{
public static bool IsUpper(string str)
{
return str.ToUpper() == str;
}
}
string s1 = "ABC";
string s2 = "cDe";
_30s.IsUpper(s1); // true
_30s.IsUpper(s2); // false
IsWeekday
- title: IsWeekday
- tags: date,utility,beginner
Returns true
if the given DateTime
is a weekday, false
otherwise.
- Use
DateTime.DayOfWeek
to check if the givenDateTime
is not a Saturday or Sunday.
public static partial class _30s
{
public static bool IsWeekday(DateTime date)
{
return date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday;
}
}
_30s.IsWeekday(new DateTime(2020, 1, 15)); // true
_30s.IsWeekday(new DateTime(2020, 1, 19)); // false
IsWeekend
- title: IsWeekend
- tags: date,utility,beginner
Returns true
if the given DateTime
is a not weekday, false
otherwise.
- Use
DateTime.DayOfWeek
to check if the givenDateTime
is a Saturday or Sunday.
public static partial class _30s
{
public static bool IsWeekend(DateTime date)
{
return date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday;
}
}
_30s.IsWeekend(new DateTime(2020, 1, 15)); // false
_30s.IsWeekend(new DateTime(2020, 1, 19)); // true
KeepUpToN
- title: KeepUpToN
- tags: array,list,intermediate
Filters a collection keeping up to n
occurences of each value.
- Use
IEnumerable.Distinct()
in combination withIEnumerable.ToDictionary()
to create a dictionary with an initial count of0
for each distinct value indata
. - Use
IEnumerable.Where()
to filter out occurences after then
th one for each element, using the previously created dictionary.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<T> KeepUpToN<T>(IEnumerable<T> data, int n)
{
var occurences = data.Distinct().ToDictionary(i => i, value => 0);
return data.Where(i => occurences[i]++ < n);
}
}
int[] nums = {1, 1, 2, 3, 3, 3, 1};
_30s.KeepUpToN(nums, 2); // {1, 1, 2, 3, 3}
LCM
- title: LCM
- tags: math,recursion,intermediate
Calculates the least common multiple of the given numbers.
- Define a
_GCD()
method that determines the greatest common divisor, using recursion. - Use
_GCD()
and the fact thatLCM(x, y) = x * y / GCD(x,y)
to determine the least common multiple. - Use
IEnumerable.Aggregate()
to applyLCM()
to all the given arguments.
using System.Linq;
public static partial class _30s
{
public static int LCM(params int[] nums)
{
return nums.Aggregate((x,y) => (x * y) / _GCD(x, y));
}
private static int _GCD(int x, int y)
{
return y == 0 ? x : _GCD(y, x % y);
}
}
_30s.LCM(1, 3, 4, 5); // 60
_30s.LCM(new [] {12, 7}); // 84
Mask
- title: Mask
- tags: string,utility,intermediate
Replaces all but the last n
characters in a string with the specified mask
character.
- Use
string.Substring()
to get the lastn
characters of the passed string,str
. - Use
string.PadLeft()
to add as manymask
characters as necessary to the start of the string to return a string of the same length. - Omit the third argument,
mask
, to use a default character of'*'
. - Omit the second argument,
n
, to keep a default of4
characters unmasked.
public static partial class _30s
{
public static string Mask(string str, int n = 4, char mask = '*')
{
return str.Substring(str.Length - n).PadLeft(str.Length, mask);
}
}
string s = "1234567890";
_30s.Mask(s); // "******7890"
_30s.Mask(s, 3); // "*******890"
_30s.Mask(s, 2, '/$'); // "$$$$$$$$90"
MaxBy
- title: MaxBy
- tags: math,list,array,lambda,intermediate
Returns the maximum of a collection, after mapping each element to a value using the provided function.
- Use
IEnumerable.Select()
to map each element to the value returned by the provided selector function,fn
. - Use
IEnumerable.Max()
to get the maximum of the resulting values.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static double MaxBy<T>(IEnumerable<T> values, Func<T,int> fn)
{
return values.Select(fn).Max();
}
}
var p = new [] {
new { a = 3, b = 2},
new { a = 2, b = 1}
};
_30s.MaxBy(p, v => v.a); // 3
_30s.MaxBy(p, v => v.b); // 2
MaxDateTime
- title: MaxDateTime
- tags: date,beginner
Returns the maximum of two DateTime
values.
- Use the conditional operator (
?:
) to return the maximum of the two values.
public static partial class _30s
{
public static DateTime MaxDateTime(DateTime d1, DateTime d2)
{
return (d1 > d2) ? d1 : d2;
}
}
DateTime d1 = new DateTime(DateTime.MaxValue.Ticks);
DateTime d2 = new DateTime(DateTime.MinValue.Ticks);
_30s.MaxDateTime(d1, d2); // 12/31/9999 11:59:59 PM
Median
- title: Median
- tags: math,intermediate
Finds the median of a list of numbers.
- Use the
params
keyword to accept either an array or a variable number of arguments. - Sort the array using
Array.sort()
and find the median. - Which is either the middle element of the list, if the list length is odd or the average of the two middle elements, if the list length is even.
public static partial class _30s
{
public static double Median(params double[] values)
{
Array.Sort(values);
if (values.Length % 2 == 0)
return (values[values.Length / 2 - 1] + values[values.Length / 2]) / 2;
return (double)values[values.Length / 2];
}
}
double[] nums = { 5, 6, 7, 8 };
_30s.Median(4, 8, 1); // 4
_30s.Median(nums); // 6.5
MinBy
- title: MinBy
- tags: math,list,array,lambda,intermediate
Returns the minimum of a collection, after mapping each element to a value using the provided function.
- Use
IEnumerable.Select()
to map each element to the value returned by the provided selector function,fn
. - Use
IEnumerable.Min()
to get the minimum of the resulting values.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static double MinBy<T>(IEnumerable<T> values, Func<T,int> fn)
{
return values.Select(fn).Min();
}
}
var p = new [] {
new { a = 3, b = 2},
new { a = 2, b = 1}
};
_30s.MinBy(p, v => v.a); // 2
_30s.MinBy(p, v => v.b); // 1
MinDateTime
- title: MinDateTime
- tags: date,beginner
Returns the minimum of two DateTime
values.
- Use the conditional operator (
?:
) to return the minimum of the two values.
public static partial class _30s
{
public static DateTime MinDateTime(DateTime d1, DateTime d2)
{
return (d1 < d2) ? d1 : d2;
}
}
DateTime d1 = new DateTime(DateTime.MaxValue.Ticks);
DateTime d2 = new DateTime(DateTime.MinValue.Ticks);
_30s.MinDateTime(d1, d2); // 1/1/0001 12:00:00 AM
MostFrequent
- title: MostFrequent
- tags: array,list,intermediate
Returns the most frequent element of a collection.
- Use
IEnumerable.GroupBy()
to groupvalues
by value. - Use
IEnumerable.OrderByDescending()
in combination withIEnumerable.Count()
to order the results in descending order based on frequency. - Use
IEnumerable.First()
to get the first element and return itsKey
property, which corresponds to the element's value.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static T MostFrequent<T>(IEnumerable<T> values)
{
return values
.GroupBy(v => v)
.OrderByDescending(v => v.Count())
.First()
.Key;
}
}
int[] nums = { 1, 2, 3, 3, 2, 3 };
List<string> str = new List<string> { "a", "b", "b", "c" };
_30s.MostFrequent(nums); // 3
_30s.MostFrequent(str); // "b"
None
- title: None
- tags: array,list,lambda,overload,intermediate
Returns true
if the provided predicate function returns false
for all elements in a collection, false
otherwise.
- Use
IEnumerable.ToArray()
,Array.Exists()
to test if all elements in the collection returnfalse
based on the predicate function,match
. - Omit the predicate function,
match
, to use the overload that checks if each value isnull
by default.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static bool None<T>(IEnumerable<T> data, Predicate<T> match)
{
return !Array.Exists(data.ToArray(), match);
}
public static bool None<T>(IEnumerable<T> data)
{
return Array.Exists(data.ToArray(), val => val == null);
}
}
int[] nums = { 4, 2, 3 };
_30s.None(nums, x => x < 0); // true
_30s.None(nums); // false
PadNumber
- title: PadNumber
- tags: string,utility,beginner
Pads a given number to the specified length
.
- Use
Int32.ToString()
with an appropriate format specifier, produced using string interpolation.
public static partial class _30s
{
public static string PadNumber(int n, int length)
{
return n.ToString($"D{length}");
}
}
_30s.PadNumber(1234,6); // "001234"
RandoubleInRange
- title: RandoubleInRange
- tags: math,utility,random,beginner
Returns a random double in the specified range.
- Use
Random.NextDouble()
to generate a random value and map it to the desired range using multiplication.
public static partial class _30s
{
public static double RandoubleInRange(double min, double max)
{
return (new Random().NextDouble() * (max - min)) + min;
}
}
_30s.RandoubleInRange(0.5, 5); // 2.20486941011849
RandomIntegerInRange
- title: RandomIntegerInRange
- tags: math,utility,random,beginner
Returns a random integer in the specified range.
- Use
Random.Next()
to generate an integer in the desired range.
public static partial class _30s
{
public static int RandomIntegerInRange(int min, int max)
{
return new Random().Next(min, max);
}
}
_30s.RandomIntegerInRange(0, 5); // 2
Repeat
- title: Repeat
- tags: string,beginner
Creates a new string by repeating the given string n
times.
- Use
Enumerable.Repeat()
to repeats
n
times,string.Concat()
to convert the result to astring
.
using System.Linq;
public static partial class _30s
{
public static string Repeat(string s, int n)
{
return string.Concat(Enumerable.Repeat(s, n));
}
}
_30s.Repeat("Ha",5); // "HaHaHaHaHa"
Reverse
- title: Reverse
- tags: string,beginner
Reverses a string.
- Use
string.ToCharArray()
to convert the string to an array ofchar
,Array.Reverse()
to reverse the array. - Use
IEnumerable.ToArray()
to create an array ofchar
and pass it to anew string()
.
using System.Linq;
public static partial class _30s
{
public static void Reverse(string s)
{
return new string(s.ToCharArray().Reverse().ToArray());
}
}
string s = "Hello World";
_30s.Reverse(s); // "dlroW olleH"
Shuffle
- title: Shuffle
- tags: array,list,random,intermediate
Randomizes the order of the values of an IList
, updating the original IList
object.
- Use the Fisher-Yates algorithm to reorder the elements of the given
IList
object.
using System.Collections.Generic;
public static partial class _30s
{
public static void Shuffle<T>(IList<T> list)
{
Random rand = new Random();
for (int n = list.Count() - 1 ; n > 0 ; n--)
{
int k = rand.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
List<int> nums = new List<int> { 1, 2, 3, 4, 5, 6 };
int[] arr = { 1, 2, 3, 4, 5, 6 };
_30s.Shuffle(nums); // nums = { 3, 5, 2, 1, 4, 6 }
_30s.Shuffle(arr); // arr = { 6, 2, 5, 1, 4, 3 }
SplitLines
- title: SplitLines
- tags: string,beginner
Splits a multiline string into an array of lines.
- Use
string.Split()
with all forms of the newline separator to split the string into an array of strings.
using System.Collections.Generic;
public static partial class _30s
{
public static string[] SplitLines(string s)
{
return s.Split(new [] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
}
}
string s = "This\nis a\nmultiline\nstring.\n";
_30s.SplitLines(s); // {"This", "is a", "multiline", "string." , ""}
SplitStringBy
- title: SplitStringBy
- tags: string,utility,beginner
Splits a string into an array of strings using a multicharacter (string) separator.
- Use
string.Split()
with the givenseparator
to split the string into an array of strings.
using System.Collections.Generic;
public static partial class _30s
{
public static string[] SplitStringBy(string s, string separator)
{
return s.Split(new [] {separator}, StringSplitOptions.None);
}
}
string s = "Apples--oranges--pears";
_30s.SplitStringBy(s,"--"); // {Apples, oranges, pears}
Stringify
- title: Stringify
- tags: utility,array,list,string,beginner
Combines the elements of an enumerable object into a string.
- Use
string.Join()
to combine all elements in theIEnumerable
into astring
, usingdelimiter
. - Omit the second argument,
delimiter
, to use the default delimiter of","
.
using System.Collections.Generic;
public static partial class _30s
{
public static string Stringify<T>(IEnumerable<T> elements, string delimiter = ",")
{
return string.Join(delimiter, elements);
}
}
IList<string> s = new List<string> {"a", "b", "c"};
int[] n = {1, 2, 3};
_30s.Stringify(s); // "a,b,c"
_30s.Stringify(n, " "); // "1 2 3"
Subarray
- title: Subarray
- tags: array,intermediate
Returns a subarray of the given array starting at the given index and having the specified length.
- Use
ArraySegment()
with the given array,arr
,start
andlength
to get the subarray. - Convert the result to an array, using
ArraySegment.ToArray()
.
using System.Collections.Generic;
public static partial class _30s
{
public static T[] Subarray<T>(T[] arr, int start, int length)
{
return new ArraySegment<T>( arr, start, length ).ToArray();
}
}
int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
_30s.Subarray(nums,3,6); // {3, 4, 5, 6, 7, 8}
SumBy
- title: SumBy
- tags: math,array,list,lambda,intermediate
Returns the sum of a collection, after mapping each element to a value using the provided function.
- Use
IEnumerable.Select()
to map each element of either collection to adouble
,IEnumerable.Sum()
to sum the values.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static double SumBy<T>(IEnumerable<T> data, Func<T,double> map)
{
return data.Select(map).Sum();
}
}
var p = new[] {
new { a = 3, b = 2},
new { a = 2, b = 1}
};
_30s.SumBy(p, x => x.a); // 5
Swap
- title: Swap
- tags: utility,intermediate
Swaps the values of two variables of the same type.
- Pass both values by reference using the
ref
keyword, then use atemp
variable to swap their values.
public static partial class _30s
{
public static void Swap<T>(ref T val1, ref T val2)
{
var temp = val1;
val1 = val2;
val2 = temp;
}
}
string a = "Ipsum";
string b = "Lorem";
_30s.Swap(ref a, ref b); // a = "Lorem", b = "Ipsum"
SymmetricDifference
- title: SymmetricDifference
- tags: array,list,beginner
Returns the symmetric difference betweend two collections.
- Use
IEnumerable.Except()
to only return elements in one enumerable object and not the other. - Use
IEnumerable.Union()
to combine the result of applying that to each object.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<T> SymmetricDifference<T>(IEnumerable<T> a, IEnumerable<T> b)
{
return a.Except(b).Union(b.Except(a));
}
}
int[] a = { 1, 2, 3, 5 };
int[] b = { 1, 2, 4 };
_30s.SymmetricDifference(a, b); // { 3, 5, 4 }
SymmetricDifferenceBy
- title: SymmetricDifferenceBy
- tags: array,list,lambda,advanced
Returns the symmetric difference betweend two collections, after applying the provided function to each element of both.
- Use
IEnumerable.Select()
to map each element of either collection to the desired type. - Use
IEnumerable.Except()
to only return elements in one enumerable object and not the other. - Use
IEnumerable.Union()
to combine the result of applying that to each object.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<R> SymmetricDifferenceBy<T,R>(IEnumerable<T> a, IEnumerable<T> b, Func<T,R> map)
{
IEnumerable<R> mapA = a.Select(map);
IEnumerable<R> mapB = b.Select(map);
return mapA.Except(mapB).Union(mapB.Except(mapA));
}
}
var p = new[] {
new { a = 3, b = 2},
new { a = 2, b = 1}
};
var q = new[] {
new { a = 6, b = 2},
new { a = 6, b = 3}
};
_30s.SymmetricDifferenceBy(p, q, x => x.b); // { 1, 3 }
Tail
- title: Tail
- tags: array,list,beginner
Returns the tail of a collection.
- Use
IEnumerable.Count()
to check if the enumerable is non-empty. - Use
IEnumerable.Skip(1)
to get the whole object except for the first element. - If the enumerable object is empty, return the
default()
value for the given enumerable.
using System.Collections.Generic;
using System.Linq;
public static partial class _30s
{
public static IEnumerable<T> Tail<T>(IEnumerable<T> list)
{
return list.Count() != 0 ? list.Skip(1) : default(IEnumerable<T>);
}
}
List<int> nums = new List<int> { 1, 2, 3, 4, 5 };
char[] chars = {'A','B','C'};
_30s.Tail(nums); // { 2, 3, 4, 5 }
_30s.Tail(chars); // {'B','C'}
ToCamelCase
- title: ToCamelCase
- tags: string,regex,advanced
Converts a string to camel case.
- Use
Regex.Matches()
with an appropriate regular expression to break the string into words. - Use
string.Join()
andstring.ToLower()
to convert the words to lowercase and combine them adding - Use
CultureInfo.TextInfo.ToTitleCase()
on the result to convert it to title case,string.Replace()
with a regular expression to remove spaces afterwards. - Finally, use
IEnumerable.Select()
on the result to convert the first character to lowercase and return a string from the result.
using System.Globalization;
using System.Text.RegularExpressions;
using System.Linq;
public static partial class _30s
{
public static string ToCamelCase(string str)
{
Regex pattern = new Regex(@"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+");
return new string(
new CultureInfo("en-US", false)
.TextInfo
.ToTitleCase(
string.Join(" ", pattern.Matches(str)).ToLower()
)
.Replace(@" ", "")
.Select((x, i) => i == 0 ? char.ToLower(x) : x)
.ToArray()
);
}
}
_30s.ToCamelCase("some_database_field_name"); // "someDatabaseFieldName"
_30s.ToCamelCase("Some label that needs to be title-cased"); // "someLabelThatNeedsToBeCamelized"
_30s.ToCamelCase("some-package-name"); // "somePackageName"
_30s.ToCamelCase("some-mixed_string with spaces_underscores-and-hyphens"); // "someMixedStringWithSpacesUnderscoresAndHyphens"
ToKebabCase
- title: ToKebabCase
- tags: string,regex,intermediate
Converts a string to kebab case.
- Use
Regex.Matches()
with an appropriate regular expression to break the string into words. - Use
string.Join()
andstring.ToLower()
to convert the words to lowercase and combine them adding-
as a separator.
using System.Text.RegularExpressions;
public static partial class _30s
{
public static string ToKebabCase(string str)
{
Regex pattern = new Regex(@"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+");
return string.Join("-", pattern.Matches(str)).ToLower();
}
}
_30s.ToKebabCase("camelCase"); // "camel-case"
_30s.ToKebabCase("some text"); // "some-text"
_30s.ToKebabCase("some-mixed_string With spaces_underscores-and-hyphens"); // "some-mixed-string-with-spaces-underscores-and-hyphens"
_30s.ToKebabCase("AllThe-small Things"); // "all-the-small-things"
ToSnakeCase
- title: ToSnakeCase
- tags: string,regex,intermediate
Converts a string to snake case.
- Use
Regex.Matches()
with an appropriate regular expression to break the string into words. - Use
string.Join()
andstring.ToLower()
to convert the words to lowercase and combine them adding_
as a separator.
using System.Text.RegularExpressions;
public static partial class _30s
{
public static string ToSnakeCase(string str)
{
Regex pattern = new Regex(@"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+");
return string.Join("_", pattern.Matches(str)).ToLower();
}
}
_30s.ToSnakeCase("camelCase"); // "camel_case"
_30s.ToSnakeCase("some text"); // "some_text"
_30s.ToSnakeCase("some-mixed_string With spaces_underscores-and-hyphens"); // "some_mixed_string_with_spaces_underscores_and_hyphens"
_30s.ToSnakeCase("AllThe-small Things"); // "all_the_small_things"
ToTitleCase
- title: ToTitleCase
- tags: string,regex,intermediate
Converts a string to title case.
- Use
Regex.Matches()
with an appropriate regular expression to break the string into words. - Use
string.Join()
andstring.ToLower()
to convert the words to lowercase and combine them adding - Use
CultureInfo.TextInfo.ToTitleCase()
on the result to convert it to title case.
using System.Globalization;
using System.Text.RegularExpressions;
public static partial class _30s
{
public static string ToTitleCase(string str)
{
Regex pattern = new Regex(@"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+");
return new CultureInfo("en-US", false)
.TextInfo
.ToTitleCase(
string.Join(" ", pattern.Matches(str)).ToLower()
);
}
}
_30s.ToTitleCase("some_database_field_name"); // "Some Database Field Name"
_30s.ToTitleCase("Some label that needs to be title-cased"); // "Some Label That Needs To Be Title Cased"
_30s.ToTitleCase("some-package-name"); // "Some Package Name"
_30s.ToTitleCase("some-mixed_string with spaces_underscores-and-hyphens"); // "Some Mixed String With Spaces Underscores And Hyphens"
Tomorrow
- title: Tomorrow
- tags: date,beginner
Returns tomorrow's DateTime
value.
- Use
DateTime.Now
to get the current date, then useDateTime.AddDays(1)
to increment by1
.
public static partial class _30s
{
public static DateTime Tomorrow()
{
return DateTime.Now.AddDays(1);
}
}
_30s.Tomorrow(); // 12/22/2019 11:00:49 AM (if it's 12/21/2019 11:00:49 AM)
Yesterday
- title: Yesterday
- tags: date,beginner
Returns yesterday's DateTime
value.
- Use
DateTime.Now
to get the current date, then useDateTime.AddDays(-1)
to decrement by1
.
public static partial class _30s
{
public static DateTime Yesterday()
{
return DateTime.Now.AddDays(-1);
}
}
_30s.Yesterday(); // 12/20/2019 11:00:49 AM (if it's 12/21/2019 11:00:49 AM)