Converte uma matriz de objetos em uma sequência de valores separados por vírgula (CSV) que contém apenas as columns especificadas.
// TODO // TODO
↑ de volta ao topo
Pega qualquer número de objetos ou objetos iteráveis com uma propriedade length e retorna o mais longo. Se vários objetos tiverem o mesmo comprimento, o primeiro será devolvido. Retorna -1 se nenhum argumento for fornecido.
// TODO // TODO
↑ de volta ao topo
Retorna os elementos n máximos da matriz fornecida. Se n for maior ou igual ao comprimento da matriz fornecida, retorne a matriz original (classificada em ordem decrescente).
// TODO // TODO
↑ de volta ao topo
Retorna os n elementos mínimos da matriz fornecida. Se n for maior ou igual ao comprimento da matriz fornecida, retorne a matriz original (classificada em ordem ascendente).
// TODO // TODO
↑ de volta ao topo
Retorna true se a função predicada fornecida retornar false para todos os elementos em uma coleção, false caso contrário.
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
↑ de volta ao topo
Retorna o enésimo elemento de uma matriz.
// TODO // TODO
↑ de volta ao topo
Move a quantidade especificada de elementos para o final da matriz.
// TODO // TODO
↑ de volta ao topo
Classifica uma coleção de matrizes.
// TODO // TODO
↑ de volta ao topo
Agrupa os elementos em duas matrizes, dependendo da verraca da função fornecida para cada elemento.
// TODO // TODO
↑ de volta ao topo
Gera todas as permutações dos elementos de uma matriz (contém duplicatas).
// TODO // TODO
↑ de volta ao topo
Recupera todos os valores para uma determinada chave.
// TODO // TODO
↑ de volta ao topo
Mastá a matriz original para filtrar os valores especificados.
// TODO // TODO
↑ de volta ao topo
Mutados a matriz original para filtrar os valores nos índices especificados.
// TODO // TODO
↑ de volta ao topo
Mastá a matriz original para filtrar os valores especificados. Retorna os elementos removidos.
// TODO // TODO
↑ de volta ao topo
Mutados a matriz original para filtrar os valores especificados, com base em uma dada função de iterador.
// TODO // TODO
↑ de volta ao topo
Filtre uma matriz de objetos com base em uma condição e também filtra as teclas não especificadas.
// TODO // TODO
↑ de volta ao topo
Aplica uma função contra um acumulador e cada elemento na matriz (da esquerda para a direita), retornando uma matriz de valores reduzidos sucessivamente.
// TODO // TODO
↑ de volta ao topo
Retorna o valor mínimo/máximo de uma matriz, após aplicar a função fornecida para definir a regra de comparação.
// TODO // TODO
↑ de volta ao topo
Tome um predicado e matriz, como Array.prototype.filter() , mas apenas mantém x se pred(x) === false .
// TODO // TODO
↑ de volta ao topo
Remove os elementos de uma matriz para a qual a função fornecida retorna false .
// TODO // TODO
↑ de volta ao topo
Retorna um elemento aleatório de uma matriz.
// TODO // TODO
↑ de volta ao topo
Obtém n elementos aleatórios em teclas exclusivas da array até o tamanho da array .
// TODO // TODO
↑ de volta ao topo
Este método altera o conteúdo de uma matriz removendo elementos existentes e/ou adicionando novos elementos. Semelhante à versão JavaScript Array.prototype.splice()
// TODO // TODO
↑ de volta ao topo
Randomiza a ordem dos valores de uma matriz, retornando uma nova matriz.
// TODO // TODO
↑ de volta ao topo
Retorna uma variedade de elementos que aparecem nas duas matrizes.
// TODO // TODO
↑ de volta ao topo
Retorna 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 ;
}
}
}Usa 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
↑ de volta ao topo
Retorna o menor índice no qual o valor deve ser inserido na matriz para manter sua ordem de classificação.
// TODO // TODO
↑ de volta ao topo
Retorna o índice mais baixo no qual o valor deve ser inserido na matriz para manter sua ordem de classificação, com base na função de iterador.
// TODO // TODO
↑ de volta ao topo
Retorna o índice mais alto no qual o valor deve ser inserido na matriz para manter sua ordem de classificação.
// TODO // TODO
↑ de volta ao topo
Retorna o índice mais alto no qual o valor deve ser inserido na matriz para manter sua ordem de classificação, com base em uma função de iterador.
// TODO // TODO
↑ de volta ao topo
Executa a classificação estável de uma matriz, preservando os índices iniciais dos itens quando seus valores são os mesmos. Não sofre a matriz original, mas retorna uma nova matriz.
// TODO // TODO
↑ de volta ao topo
Retorna a diferença simétrica entre duas matrizes, sem filtrar valores duplicados.
// TODO // TODO
↑ de volta ao topo
Retorna a diferença simétrica entre duas matrizes, depois de aplicar a função fornecida a cada elemento da matriz de ambos.
// TODO // TODO
↑ de volta ao topo
Retorna a diferença simétrica entre duas matrizes, usando uma função fornecida como comparador.
// TODO // TODO
↑ de volta ao topo
Retorna todos os elementos em uma matriz, exceto o primeiro.
// TODO // TODO
↑ de volta ao topo
Retorna uma matriz com n elementos removidos desde o início.
// TODO // TODO
↑ de volta ao topo
Retorna uma matriz com n elementos removidos do final.
// TODO // TODO
↑ de volta ao topo
Remove os elementos do final de uma matriz até que a função passada retorne true . Retorna os elementos removidos.
// TODO // TODO
↑ de volta ao topo
Remove os elementos em uma matriz até que a função passada retorne true . Retorna os elementos removidos.
// TODO // TODO
↑ de volta ao topo
Converte uma 2D enumerável em uma string de valores separados por vírgula (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"
↑ de volta ao topo
Reduz uma determinada matriz em um hash de valor (armazenamento de dados com chave).
// TODO // TODO
↑ de volta ao topo
Retorna todos os elementos que existam em qualquer uma das duas matrizes uma vez.
// TODO // TODO
↑ de volta ao topo
Retorna todos os elementos que existam em qualquer uma das duas matrizes uma vez, depois de aplicar a função fornecida a cada elemento da matriz de ambos.
// TODO // TODO
↑ de volta ao topo
Retorna todos os elementos que existam em qualquer uma das duas matrizes uma vez, usando uma função comparadora fornecida.
// TODO // TODO
↑ de volta ao topo
Retorna todos os valores únicos de uma matriz.
// TODO // TODO
↑ de volta ao topo
Retorna todos os valores exclusivos de uma matriz, com base em uma função de comparador fornecida.
// TODO // TODO
↑ de volta ao topo
Retorna todos os valores exclusivos de uma matriz, com base em uma função de comparador fornecida.
// TODO // TODO
↑ de volta ao topo
Retorna a diferença simétrica exclusiva entre duas matrizes, não contendo valores duplicados de qualquer uma das matrizes.
// TODO // TODO
↑ de volta ao topo
Filtra os elementos de uma matriz, que possuem um dos valores especificados.
// TODO // TODO
↑ de volta ao topo
Cria uma nova matriz dos dois fornecidos criando cada par possível a partir das matrizes.
// TODO // TODO
↑ de volta ao topo
Verifica se dois números são aproximadamente iguais um ao outro.
// TODO // TODO
↑ de volta ao topo
Retorna a média de dois ou mais números.
O método, exceto os números como parâmetros e retorna a média como resultado.
Documentação do LINQ aqui.
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
↑ de volta ao topo
Retorna a média de uma matriz, depois de mapear cada elemento para um valor usando a função fornecida.
// TODO // TODO
↑ de volta ao topo
Avalia o coeficiente binomial de dois números inteiros n e k .
// TODO // TODO
↑ de volta ao topo
Converte um ângulo de graus em radianos.
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
↑ de volta ao topo
Converte um número em uma matriz de dígitos.
// TODO // TODO
↑ de volta ao topo
Retorna a distância entre dois pontos.
// TODO // TODO
↑ de volta ao topo
Calcula o fatorial de um número.
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
↑ de volta ao topo
Gera uma lista, contendo a sequência de Fibonacci, até o enésimo termo.
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 }
↑ de volta ao topo
Calcula o maior divisor comum entre dois ou mais números/matrizes.
// TODO // TODO
↑ de volta ao topo
Inicializa uma matriz que contém os números no intervalo especificado, onde start e end são inclusivos e a proporção entre dois termos é step . Retorna um erro se step é igual a 1 .
// TODO // TODO
↑ de volta ao topo
Verifica se o número fornecido se enquadra no intervalo fornecido.
// TODO // TODO
↑ de volta ao topo
Verifica se um número é divisível por outro número.
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
↑ de volta ao topo
Retorna true se o número fornecido for mesmo, false caso contrário.
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
↑ de volta ao topo
Verifica se o número inteiro fornecido é um número primo.
// TODO // TODO
↑ de volta ao topo
Retorna true se o número fornecido for estranho, false caso contrário.
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
↑ de volta ao topo
Retorna o múltiplo menos comum de dois ou mais números.
// TODO // TODO
↑ de volta ao topo
Implementação do algoritmo Luhn usado para validar uma variedade de números de identificação, como números de cartão de crédito, números de IMEI, números de identificadores de fornecedores nacionais etc.
// TODO // TODO
↑ de volta ao topo
Retorna o valor máximo do enumerável fornecido.
// TODO // TODO
↑ de volta ao topo
Retorna a mediana de uma variedade de números.
// TODO // TODO
↑ de volta ao topo
Retorna o valor mínimo do enumerável fornecido.
// TODO // TODO
↑ de volta ao topo
Gera primos até um determinado número, usando a peneira de eratóstenes.
// TODO // TODO
↑ de volta ao topo
Converte um ângulo de radianos em graus.
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
↑ de volta ao topo
Retorna uma matriz de n números inteiros aleatórios no intervalo especificado.
// TODO // TODO
↑ de volta ao topo
Retorna um número inteiro aleatório no intervalo especificado.
// TODO // TODO
↑ de volta ao topo
Retorna um número aleatório no intervalo especificado.
// TODO // TODO
↑ de volta ao topo
Receita um número para uma quantidade especificada de dígitos.
// TODO // TODO
↑ de volta ao topo
Hashes a sequência de entrada em um número inteiro.
// TODO // TODO
↑ de volta ao topo
Retorna o desvio padrão de uma variedade de números.
// TODO // TODO
↑ de volta ao topo
Retorna a soma de dois ou mais números/matrizes.
// TODO // TODO
↑ de volta ao topo
Retorna a soma de uma matriz, depois de mapear cada elemento para um valor usando a função fornecida.
// TODO // TODO
↑ de volta ao topo
Retorna o número de vezes uma função executada por segundo. hz é a unidade de hertz , a unidade de frequência definida como um ciclo por segundo.
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 ) ;
↑ de volta ao topo
Itera mais de um retorno de chamada n vezes
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
↑ de volta ao topo
Retorna o comprimento de uma corda em 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 ) ;
}
} // TODO
↑ de volta ao topo
Retorna o número de vogais na string fornecida.
"" . ByteSize ( ) ; # 0
"Hello World" . ByteSize ( ) ; # 11
"Hello World" . ByteSizeUnicode ( ) ; # 22
"Hello World" . ByteSizeUtf32 ( ) ; # 44
"This is 30 seconds of C." . ByteSizeBigEndianUnicode ( ) ; # 48 // TODO
↑ de volta ao topo
Converte uma sequência de valores separados por vírgula (CSV) em uma matriz 2D.
// TODO // TODO
↑ de volta ao topo
Converte uma sequência de valores separados por vírgula (CSV) em uma matriz 2D de objetos. A primeira linha da string é usada como a linha do título.
// TODO // TODO
↑ de volta ao topo
Verifique se uma string termina com uma determinada substring usando um regex.
O método, exceto a sequência para testar e uma substring para testar.
A maioria das outras verificações já está integrada.
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
↑ de volta ao topo
Converte uma corda de Camelcase. Torna todas as palavras minúsculas e combina -as usando um separador fornecido (o padrão é um espaço em branco). Do paramsEntence == true, a primeira letra da frase será maiúscula e um ponto será adicionado no final (o padrão é verdadeiro).
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"
↑ de volta ao topo
Verifica se uma string é um anagrama de outra string (insensível com o caso).
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
↑ de volta ao topo
Verifica se uma string é minúscula.
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
↑ de volta ao topo
Retorna true se a string fornecida for um palíndromo, false caso contrário.
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
↑ de volta ao topo
Verifica se uma string é mais alta.
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
↑ de volta ao topo
Substitui todos, exceto o último length dos caracteres pelo caractere mask especificado. Omita o segundo argumento, length , para manter um padrão de 4 caracteres desmascarados. Se length for negativo, os caracteres desmascarados estarão no início da string. Omita o terceiro argumento, mask , para usar um caractere padrão de '*' para a máscara.
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"
↑ de volta ao topo
Ponta uma corda de ambos os lados com o caractere especificado, se for mais curto que o comprimento especificado. Use PadLeft() e PadRight() para encaixar os dois lados da corda fornecida. Omita o terceiro argumento, char , para usar o personagem Whitespace como o caractere de preenchimento padrão.
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"
↑ de volta ao topo
Remove caracteres ASCII não impressos. Use uma expressão regular para remover caracteres ASCII não impressos.
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"
↑ de volta ao topo
Reverte uma string.
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!"
↑ de volta ao topo
Divide uma corda multilina em uma variedade de linhas.
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." , "" }
↑ de volta ao topo
Verifique se uma string inicia com uma determinada substring usando um regex.
O método, exceto a sequência para testar e uma substring para testar.
A maioria das outras verificações já está integrada.
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
↑ de volta ao topo
Remove tags html/xml da string. Use uma expressão regular para remover tags HTML/XML de uma string.
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"
↑ de volta ao topo
Converte uma corda em 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"
↑ de volta ao topo
Converte uma string em estojo 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"
↑ de volta ao topo
Converte um caso de string em cobra.
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"
↑ de volta ao topo
Converte uma string em caso de título.
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"
↑ de volta ao topo
Trunca uma string até um comprimento especificado.
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"
↑ de volta ao topo
Converte uma determinada string em uma lista de palavras.
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 > ( )
↑ de volta ao topo
Verifica se o tipo fornecido é do tipo numérico.
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
↑ de volta ao topo
Estende um código de cores de 3 dígitos para um código de cores de 6 dígitos.
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"
↑ de volta ao topo
Converte um código de cores em uma sequência rgb() ou rgba() se o valor alfa for fornecido.
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)"
↑ de volta ao topo
Converte um número em bytes em uma string legível por humanos.
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"
↑ de volta ao topo
Gera uma cor hexadecimal aleatória.
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 . )
↑ de volta ao topo
Converte os valores dos componentes RGB em um código de cores.
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"
↑ de volta ao topo
Mede o tempo gasto por uma função para executar.
Documentação de parada aqui.
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
↑ de volta ao topo
Retorna true se a string for y / yes ou false se a string for 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
↑ de volta ao topo
Você sempre é convidado a contribuir com este projeto. Por favor, leia o guia de contribuição.
| Jonas Schubert | Denis Biondic |
30 segundos de C# são distribuídos sob a licença do MIT. Consulte a licença para obter detalhes.
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.