Convertit un tableau d'objets en une chaîne de valeurs séparées par des virgules (CSV) qui ne contient que les columns spécifiées.
// TODO // TODO
↑ Retour au sommet
Prend n'importe quel nombre d'objets ou d'objets itérables avec une propriété length et renvoie la plus longue. Si plusieurs objets ont la même longueur, le premier sera retourné. Renvoie -1 si aucun argument n'est fourni.
// TODO // TODO
↑ Retour au sommet
Renvoie les n éléments maximum du tableau fourni. Si n est supérieur ou égal à la longueur du tableau fourni, retournez le tableau d'origine (trié dans l'ordre descendant).
// TODO // TODO
↑ Retour au sommet
Renvoie les n éléments minimaux du tableau fourni. Si n est supérieur ou égal à la longueur du tableau fourni, retournez le tableau d'origine (trié par ordre croissant).
// TODO // TODO
↑ Retour au sommet
Renvoie true si la fonction de prédicat fournie renvoie false pour tous les éléments d'une collection, false autrement.
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 ;
}
}
}
} 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
↑ Retour au sommet
Renvoie le nième élément d'un tableau.
// TODO // TODO
↑ Retour au sommet
Déplace la quantité spécifiée d'éléments à la fin du tableau.
// TODO // TODO
↑ Retour au sommet
Trie une collection de tableaux.
// TODO // TODO
↑ Retour au sommet
Groupe les éléments en deux tableaux, en fonction de la vérité de la fonction fournie pour chaque élément.
// TODO // TODO
↑ Retour au sommet
Génère toutes les permutations des éléments d'un tableau (contient des doublons).
// TODO // TODO
↑ Retour au sommet
Récupère toutes les valeurs pour une clé donnée.
// TODO // TODO
↑ Retour au sommet
Mutate le tableau d'origine pour filtrer les valeurs spécifiées.
// TODO // TODO
↑ Retour au sommet
Mutate le tableau d'origine pour filtrer les valeurs aux index spécifiés.
// TODO // TODO
↑ Retour au sommet
Mutate le tableau d'origine pour filtrer les valeurs spécifiées. Renvoie les éléments supprimés.
// TODO // TODO
↑ Retour au sommet
Mutate le tableau d'origine pour filtrer les valeurs spécifiées, en fonction d'une fonction itératrice donnée.
// TODO // TODO
↑ Retour au sommet
Filtrez un tableau d'objets en fonction d'une condition tout en filtrant également les clés non spécifiées.
// TODO // TODO
↑ Retour au sommet
Applique une fonction contre un accumulateur et chaque élément du tableau (de gauche à droite), renvoyant un tableau de valeurs successivement réduites.
// TODO // TODO
↑ Retour au sommet
Renvoie la valeur minimale / maximale d'un tableau, après avoir appliqué la fonction fournie pour définir la règle de comparaison.
// TODO // TODO
↑ Retour au sommet
Prend un prédicat et un tableau, comme Array.prototype.filter() , mais ne conserve x que si pred(x) === false .
// TODO // TODO
↑ Retour au sommet
Supprime les éléments d'un tableau pour lequel la fonction donnée renvoie false .
// TODO // TODO
↑ Retour au sommet
Renvoie un élément aléatoire d'un tableau.
// TODO // TODO
↑ Retour au sommet
Obtient n éléments aléatoires à des clés uniques du array jusqu'à la taille du array .
// TODO // TODO
↑ Retour au sommet
Cette méthode modifie le contenu d'un tableau en supprimant les éléments existants et / ou en ajoutant de nouveaux éléments. Similaire à la version JavaScript Array.prototype.splice()
// TODO // TODO
↑ Retour au sommet
Randomise l'ordre des valeurs d'un tableau, renvoyant un nouveau tableau.
// TODO // TODO
↑ Retour au sommet
Renvoie un tableau d'éléments qui apparaissent dans les deux tableaux.
// TODO // TODO
↑ Retour au sommet
Renvoie Direction.Descending Direction.Ascending Direction.NotSorted
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 ;
}
}
}Utilise enum jonasschubert.snippets.enumerable.direction.
public enum Direction
{
NotSorted ,
Ascending ,
Descending
} 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
↑ Retour au sommet
Renvoie l'index le plus bas auquel la valeur doit être insérée dans le tableau afin de maintenir son ordre de tri.
// TODO // TODO
↑ Retour au sommet
Renvoie l'index le plus bas à laquelle la valeur doit être insérée dans le tableau afin de maintenir son ordre de tri, en fonction d'une fonction itératrice fournie.
// TODO // TODO
↑ Retour au sommet
Renvoie l'indice le plus élevé auquel la valeur doit être insérée dans le tableau afin de maintenir son ordre de tri.
// TODO // TODO
↑ Retour au sommet
Renvoie l'index le plus élevé auquel la valeur doit être insérée dans le tableau afin de maintenir son ordre de tri, en fonction d'une fonction itératrice fournie.
// TODO // TODO
↑ Retour au sommet
Effectue un tri stable d'un tableau, en préservant les index initiaux des éléments lorsque leurs valeurs sont les mêmes. Ne mute pas le tableau d'origine, mais renvoie un nouveau tableau à la place.
// TODO // TODO
↑ Retour au sommet
Renvoie la différence symétrique entre deux tableaux, sans filtrer les valeurs en double.
// TODO // TODO
↑ Retour au sommet
Renvoie la différence symétrique entre deux tableaux, après avoir appliqué la fonction fournie à chaque élément de tableau des deux.
// TODO // TODO
↑ Retour au sommet
Renvoie la différence symétrique entre deux tableaux, en utilisant une fonction fournie comme comparateur.
// TODO // TODO
↑ Retour au sommet
Renvoie tous les éléments dans un tableau, sauf pour le premier.
// TODO // TODO
↑ Retour au sommet
Renvoie un tableau avec N éléments supprimés depuis le début.
// TODO // TODO
↑ Retour au sommet
Renvoie un tableau avec N éléments supprimés de la fin.
// TODO // TODO
↑ Retour au sommet
Supprime les éléments de la fin d'un tableau jusqu'à ce que la fonction passée renvoie true . Renvoie les éléments supprimés.
// TODO // TODO
↑ Retour au sommet
Supprime les éléments dans un tableau jusqu'à ce que la fonction passée renvoie true . Renvoie les éléments supprimés.
// TODO // TODO
↑ Retour au sommet
Convertit une énumération 2D en une chaîne de valeurs séparées par des virgules (CSV).
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 ( ) ) ) ) ) ;
}
}
} new List < List < bool > > { new List < bool > { true , true } , new List < bool > { true , false } } . ToCsv ( ) ; # "True,True n True,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 n 4.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 n Byte: 1-Byte: 2"
↑ Retour au sommet
Réduit un tableau donné comme un hachage de valeur (magasin de données Keyed).
// TODO // TODO
↑ Retour au sommet
Renvoie chaque élément qui existe dans l'un des deux tableaux une fois.
// TODO // TODO
↑ Retour au sommet
Renvoie chaque élément qui existe dans l'un des deux tableaux une fois, après avoir appliqué la fonction fournie à chaque élément de tableau des deux.
// TODO // TODO
↑ Retour au sommet
Renvoie chaque élément qui existe dans l'un des deux tableaux une fois, en utilisant une fonction de comparateur fournie.
// TODO // TODO
↑ Retour au sommet
Renvoie toutes les valeurs uniques d'un tableau.
// TODO // TODO
↑ Retour au sommet
Renvoie toutes les valeurs uniques d'un tableau, en fonction d'une fonction de comparateur fournie.
// TODO // TODO
↑ Retour au sommet
Renvoie toutes les valeurs uniques d'un tableau, en fonction d'une fonction de comparateur fournie.
// TODO // TODO
↑ Retour au sommet
Renvoie la différence symétrique unique entre deux tableaux, sans contenir des valeurs en double de l'un ou l'autre tableau.
// TODO // TODO
↑ Retour au sommet
Filtre les éléments d'un tableau, qui ont l'une des valeurs spécifiées.
// TODO // TODO
↑ Retour au sommet
Crée un nouveau tableau des deux fournis en créant chaque paire possible à partir des tableaux.
// TODO // TODO
↑ Retour au sommet
Vérifie si deux nombres sont approximativement égaux les uns aux autres.
// TODO // TODO
↑ Retour au sommet
Renvoie la moyenne de deux nombres ou plus.
La méthode saute les nombres en paramètres et renvoie la moyenne en conséquence.
Documentation LINQ ici.
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 ;
}
}
} { 4 , 5 , 9 , 1 , 0 } . Average ( ) # 3.8
↑ Retour au sommet
Renvoie la moyenne d'un tableau, après avoir cartographié chaque élément à une valeur en utilisant la fonction fournie.
// TODO // TODO
↑ Retour au sommet
Évalue le coefficient binomial de deux entiers n et k .
// TODO // TODO
↑ Retour au sommet
Convertit un angle entre les degrés en 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 ;
}
} 270.0 . DegToRad ( ) ; # ~ 4.71
- 90u . DegToRad ( ) ; # ~ 1.57
720 . DegToRad ( ) ; # ~ 12.57
↑ Retour au sommet
Convertit un nombre en un tableau de chiffres.
// TODO // TODO
↑ Retour au sommet
Renvoie la distance entre deux points.
// TODO // TODO
↑ Retour au sommet
Calcule le factoriel d'un nombre.
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 ;
}
}
} Math . Factorial ( 0 ) ; # 1
Math . Factorial ( 3 ) ; # 6
Math . Factorial ( 6 ) ; # 720
↑ Retour au sommet
Génère une liste, contenant la séquence de Fibonacci, jusqu'au nième terme.
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 ;
}
}
} Math . Fibonaci ( 2 ) ; # n ew List < int > ( ) { 0 , 1 }
Math . Fibonaci ( 7 ) ; # n ew List < int > ( ) { 0 , 1 , 1 , 2 , 3 , 5 , 8 }
↑ Retour au sommet
Calcule le plus grand diviseur commun entre deux ou plusieurs nombres / tableaux.
// TODO // TODO
↑ Retour au sommet
Initialise un tableau contenant les nombres dans la plage spécifiée où start et end sont inclusifs et le rapport entre deux termes est step . Renvoie une erreur si step équivaut 1 .
// TODO // TODO
↑ Retour au sommet
Vérifie si le nombre donné se situe dans la plage donnée.
// TODO // TODO
↑ Retour au sommet
Vérifie si le nombre est divisible par un autre numéro.
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 ;
}
} 1 . IsDivisibleBy ( 2 ) ; # true
- 2.0 . IsDivisibleBy ( 2.0 ) ; # true
1.0f . IsDivisibleBy ( 2.0f ) ; # false
2u . IsDivisibleBy ( 2u ) ; # true
↑ Retour au sommet
Renvoie true si le nombre donné est uniforme, false sinon.
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 ;
}
} 0 . IsEven ( ) ; # true
1u . IsEven ( ) ; # false
- 2.0 . IsEven ( ) ; # true
↑ Retour au sommet
Vérifie si l'entier fourni est un nombre premier.
// TODO // TODO
↑ Retour au sommet
Renvoie true si le nombre donné est impair, false sinon.
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 ;
}
} 0 . IsOdd ( ) ; # false
1u . IsOdd ( ) ; # true
- 2.0 . IsOdd ( ) ; # false
↑ Retour au sommet
Renvoie le multiple le moins commun de deux nombres ou plus.
// TODO // TODO
↑ Retour au sommet
La mise en œuvre de l'algorithme Luhn utilisé pour valider une variété de numéros d'identification, tels que les numéros de carte de crédit, les numéros IMEI, les numéros d'identifiant du fournisseur national, etc.
// TODO // TODO
↑ Retour au sommet
Renvoie la valeur maximale de l'énumérable fourni.
// TODO // TODO
↑ Retour au sommet
Renvoie la médiane d'un éventail de nombres.
// TODO // TODO
↑ Retour au sommet
Renvoie la valeur minimale de l'énumérable fourni.
// TODO // TODO
↑ Retour au sommet
Génère des nombres premiers à un nombre donné, en utilisant le tamis des eratosthènes.
// TODO // TODO
↑ Retour au sommet
Convertit un angle de radians en degrés.
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 ;
}
} ( System . Math . PI / 2 ) . RadToDeg ( ) # 90
( System . Math . PI * - 2 ) . RadToDeg ( ) # - 360
↑ Retour au sommet
Renvoie un tableau de n entiers aléatoires dans la plage spécifiée.
// TODO // TODO
↑ Retour au sommet
Renvoie un entier aléatoire dans la plage spécifiée.
// TODO // TODO
↑ Retour au sommet
Renvoie un nombre aléatoire dans la plage spécifiée.
// TODO // TODO
↑ Retour au sommet
Arrête un nombre à un nombre spécifié de chiffres.
// TODO // TODO
↑ Retour au sommet
Hache la chaîne d'entrée dans un numéro entier.
// TODO // TODO
↑ Retour au sommet
Renvoie l'écart type d'un tableau de nombres.
// TODO // TODO
↑ Retour au sommet
Renvoie la somme de deux ou plusieurs nombres / tableaux.
// TODO // TODO
↑ Retour au sommet
Renvoie la somme d'un tableau, après avoir cartographié chaque élément à une valeur en utilisant la fonction fournie.
// TODO // TODO
↑ Retour au sommet
Renvoie le nombre de fois une fonction exécutée par seconde. hz est l'unité de hertz , l'unité de fréquence définie comme un cycle par seconde.
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 ;
}
.. .
}
} # w ill 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 ) ;
↑ Retour au sommet
Itérer sur un rappel n fois
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 ;
}
}
} 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
↑ Retour au sommet
Renvoie la longueur d'une chaîne en octets.
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 ) ;
}
} // TODO
↑ Retour au sommet
Renvoie le nombre de voyelles dans la chaîne fournie.
"" . ByteSize ( ) ; # 0
"Hello World" . ByteSize ( ) ; # 11
"Hello World" . ByteSizeUnicode ( ) ; # 22
"Hello World" . ByteSizeUtf32 ( ) ; # 44
"This is 30 seconds of C." . ByteSizeBigEndianUnicode ( ) ; # 48 // TODO
↑ Retour au sommet
Convertit une chaîne de valeurs séparées par des virgules (CSV) en un tableau 2D.
// TODO // TODO
↑ Retour au sommet
Convertit une chaîne de valeurs séparées par des virgules (CSV) en un tableau 2D d'objets. La première ligne de la chaîne est utilisée comme ligne de titre.
// TODO // TODO
↑ Retour au sommet
Vérifiez si une chaîne se termine par une sous-chaîne donnée à l'aide d'un regex.
La méthode sauve la chaîne à tester et une sous-chaîne contre laquelle tester.
La plupart des autres chèques sont déjà intégrés.
namespace JonasSchubert . Snippets . String
{
public static partial class String
{
public static bool EndsWithRegex ( this string input , string substring ) => new Regex ( $ " { substring } $" ) . IsMatch ( input ) ;
}
} "Hello World" . EndsWithRegex ( @"[dolrwDOLRW]{5}$" ) # true
"Hello World, this is it" . EndsWithRegex ( @"[dolrwDOLRW]{5}$" ) # false
↑ Retour au sommet
Convertit une chaîne de camelcase. Fait tous les mots minuscules et les combine à l'aide d'un séparateur fourni (par défaut est un espace blanc). De la paramètres == true, la première lettre de la phrase sera en majuscule et un point sera ajouté à la fin (la valeur par défaut est vraie).
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 ;
}
}
} "someDatabaseFieldName" . FromCamelCase ( ) ; # "Some database field name."
"someLabelThatNeedsToBeCamelized" . FromCamelCase ( "-" , false ) ; # "some-label-that-needs-to-be-camelized"
"someJavascriptProperty" . FromCamelCase ( "_" , false ) ; # "some_javascript_property"
↑ Retour au sommet
Vérifie si une chaîne est une anagramme d'une autre chaîne (insensible au cas).
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 ) ) ;
}
} "iceman" . IsAnagramOf ( "cinema" ) ; # true
"icemAn" . IsAnagramOf ( "cinema" ; # true
"icem an" . IsAnagramOf ( "cinema" ; # false
"ic.EMan" . IsAnagramOf ( "cinema" ; # false
"icman" . IsAnagramOf ( "cinema" ; # false
↑ Retour au sommet
Vérifie si une chaîne est minuscule.
namespace JonasSchubert . Snippets . String
{
public static partial class String
{
public static bool IsLower ( this string input ) => input == input . ToLower ( ) ;
}
} "abc" . IsLower ( ) ; # true
"a3@$" . IsLower ( ) ; # true
"Ab4" . IsLower ( ) ; # false
↑ Retour au sommet
Renvoie true si la chaîne donnée est un palindrome, false sinon.
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 ( ) ;
}
} "tacocat" . IsPalindrome ( ) ; # true
"tAcocat" . IsPalindrome ( ) ; # true
"tacoca" . IsPalindrome ( ) ; # false
↑ Retour au sommet
Vérifie si une chaîne est en majuscules.
namespace JonasSchubert . Snippets . String
{
public static partial class String
{
public static bool IsUpper ( this string input ) => input == input . ToUpper ( ) ;
}
} "ABC" . IsUpper ( ) ; # true
"A3@$" . IsUpper ( ) ; # true
"aB4" . IsUpper ( ) ; # false
↑ Retour au sommet
Remplace toute la dernière length des caractères, sauf la dernière, par le caractère mask spécifié. Omettez le deuxième argument, length , pour garder un défaut de 4 caractères démasqué. Si length est négative, les caractères démasqués seront au début de la chaîne. Omettez le troisième argument, mask , pour utiliser un caractère par défaut de '*' pour le masque.
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 ) ) ;
}
} "1234567890" . Mask ( ) ; # "******7890"
"1234567890" . Mask ( 3 ) ; # "*******890"
"1234567890" . Mask ( 0 ) ; # "**********"
"1234567890" . Mask ( - 4 ) ; # "1234******"
"1234567890" . Mask ( 20 , '-' ) ; # "----------"
"1234567890" . Mask ( - 20 , '-' ) ; # "1234567890"
↑ Retour au sommet
Porte une chaîne des deux côtés avec le caractère spécifié, s'il est plus court que la longueur spécifiée. Utilisez PadLeft() et PadRight() pour remplir les deux côtés de la chaîne donnée. Omettez le troisième argument, char , pour utiliser le caractère Whitespace comme caractère de rembourrage par défaut.
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 ) ;
}
} "Hello World." . Pad ( 20 ) ; # " Hello World. "
"Hello World." . Pad ( 5 , '-' ) ; # "Hello World."
"Dog" . Pad ( 8 , ' ' ) ; # " Dog "
"42" . Pad ( 6 , '0' ) ; # "004200"
↑ Retour au sommet
Supprime les caractères ASCII non imprimables. Utilisez une expression régulière pour supprimer les caractères ASCII non imprimables.
namespace JonasSchubert . Snippets . String
{
public static partial class String
{
public static string RemoveNonAscii ( this string input ) => Regex . Replace ( input , "[^ x20 - x7E ]" , "" ) ;
}
} "äÄçÇéÉêlorem ipsumöÖÐþúÚ" . RemoveNonAscii ( ) ; # "lorem ipsum"
↑ Retour au sommet
Inverse une chaîne.
namespace JonasSchubert . Snippets . String
{
public static partial class String
{
public static string Reverse ( this string input ) => string . Join ( string . Empty , input . ToCharArray ( ) . Reverse ( ) ) ;
}
} "My name is Jonas Schubert" . Reverse ( ) ; # "trebuhcS sanoJ si eman yM"
"!This is, maybe not, but important..." . Reverse ( ) ; # "...tnatropmi tub ,ton ebyam ,si sihT!"
↑ Retour au sommet
Fruit une chaîne multiline dans un tableau de lignes.
namespace JonasSchubert . Snippets . String
{
public static partial class String
{
public static string [ ] SplitLines ( this string input ) => Regex . Split ( input , " r ? n " ) ;
}
} "This n is a n multiline n string. n " . SplitLines ( ) ; # n ew string [ ] { "This" , "is a" , "multiline" , "string." , "" }
↑ Retour au sommet
Vérifiez si une chaîne commence par une sous-chaîne donnée à l'aide d'un regex.
La méthode sauve la chaîne à tester et une sous-chaîne contre laquelle tester.
La plupart des autres chèques sont déjà intégrés.
namespace JonasSchubert . Snippets . String
{
public static partial class String
{
public static bool StartsWithRegex ( this string input , string substring ) => new Regex ( $ "^ { substring } " ) . IsMatch ( input ) ;
}
} "Hello World" . StartsWithRegex ( @"[ehloEHLO]{5}$" ) # true
"Well, hello World" . StartsWithRegex ( @"[ehloEHLO]{5}$" ) # false
↑ Retour au sommet
Supprime les balises HTML / XML de la chaîne. Utilisez une expression régulière pour supprimer les balises HTML / XML à partir d'une chaîne.
namespace JonasSchubert . Snippets . String
{
public static partial class String
{
public static string StripHtmlTags ( this string input ) => Regex . Replace ( input , "<[^>]*>" , "" ) ;
}
} "<p><em>lorem</em> <strong>ipsum</strong></p>" . StripHtmlTags ( ) ; # "lorem ipsum"
"<div><br/>Hello <br />World</div>" . StripHtmlTags ( ) ; # "Hello World"
↑ Retour au sommet
Convertit une chaîne en 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 ) ;
}
}
} "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"
↑ Retour au sommet
Convertit une chaîne en cas de kebab.
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 ( ) ) ) ;
}
} "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"
↑ Retour au sommet
Convertit une chaîne en cas de serpent.
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 ( ) ) ) ;
}
} "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"
↑ Retour au sommet
Convertit une chaîne en cas de titre.
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 ( ) } " ) ) ;
}
} "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"
↑ Retour au sommet
Tronque une chaîne jusqu'à une longueur spécifiée.
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 ;
}
} "Hello World" . Truncate ( 4 ) ; # "H..."
"Hello World" . Truncate ( 12 ) ; # "Hello World"
↑ Retour au sommet
Convertit une chaîne donnée en une liste de mots.
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 ( ) ;
}
} "Hello World" . Words ( ) ; # n ew List < string > { "Hello" , "World" }
"Hello" . Words ( ) ; # n ew List < string > { "Hello" }
" " . Words ( ) ; # n ew List < string > ( )
↑ Retour au sommet
Vérifie si le type fourni est de type numérique.
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 ;
}
}
}
} typeof ( sbyte ) . IsNumericType ( ) ; # true
typeof ( short ) . IsNumericType ( ) ; # true
typeof ( float ) . IsNumericType ( ) ; # true
typeof ( string ) . IsNumericType ( ) ; # false
typeof ( int [ ] ) . IsNumericType ( ) ; # false
↑ Retour au sommet
Étend un code couleur à 3 chiffres à un code couleur à 6 chiffres.
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 } " ) ) } " ;
}
} "#03f" . ExtendHex ( ) ; # "#0033ff"
"05a" . ExtendHex ( ) ; # "#0055aa"
↑ Retour au sommet
Convertit un code couleur en une chaîne rgb() ou rgba() si une valeur alpha est fournie.
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 } " : "" ) } )" ;
}
}
} Utility . HexToRgb ( "#fff" ) ; # "rgb(255, 255, 255)"
Utility . HexToRgb ( "#27ae60" ) ; # "rgb(39, 174, 96)"
Utility . HexToRgb ( "#27ae60ff" ) ; # "rgba(39, 174, 96, 255)"
↑ Retour au sommet
Convertit un nombre en octets en une chaîne lisible par l'homme.
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" ;
}
}
} 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"
↑ Retour au sommet
Génère une couleur hexadécimale aléatoire.
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 ) } " ;
}
} Utility . RandomHexColor ( ) ; # "#01A5FF" ( e . g . )
↑ Retour au sommet
Convertit les valeurs des composants RVB en code couleur.
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' ) } " ;
}
} Utility . RgbToHex ( 0 , 0 , 0 ) ; # "#000000"
Utility . RgbToHex ( 1 , 165 , 255 ) ; # "#01A5FF"
Utility . RgbToHex ( 255 , 255 , 255 ) ; # "#FFFFFF"
↑ Retour au sommet
Mesure le temps pris par une fonction à exécuter.
Documentation du chronomètre ici.
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 ) ;
}
}
} Utility . TimeTaken ( ( ) => true ) # 13.37m s , true
↑ Retour au sommet
Renvoie true si la chaîne est y / yes ou false si la chaîne est 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 ;
}
} var empty = "" . YesNo ( ) ; # false
var yes = "yes" . YesNo ( ) ; # true
var y = "y" . YesNo ( ) ; # true
var NO = "NO" . YesNo ( ) ; # false
var nO = "nO" . YesNo ( ) ; # false
↑ Retour au sommet
Vous êtes toujours invités à contribuer à ce projet. Veuillez lire le guide de contribution.
| Jonas Schubert | Denis Biondic |
30 secondes de C # sont distribuées sous la licence du MIT. Voir la licence pour plus de détails.
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.