65.9K
CodeProject is changing. Read more.
Home

Handy Extension Methods

Jun 6, 2011

CPOL
viewsIcon

7920

public static bool IsInString(this char c, string range){ return range.Contains(c.ToString());}public static bool IsInteger(this string text){ int num; return int.TryParse(text, out num);}public static bool IsNullOrEmpty(this string str){ return...

public static bool IsInString(this char c, string range)
{
    return range.Contains(c.ToString());
}
public static bool IsInteger(this string text)
{
    int num;
    return int.TryParse(text, out num);
}
public static bool IsNullOrEmpty(this string str)
{
    return string.IsNullOrEmpty(str);
}
public static string IsNull(this string str, string defaultValue)
{
    return str.IsNullOrEmpty() ? defaultValue : str;
}
public static bool IsNumber(this string text)
{
    float num;
    return float.TryParse(text, out num);
}
public static bool IsUnicode(this string str)
{
    byte[] unicodeBytes = Encoding.Unicode.GetBytes(str);
    for (int i = 1; i < unicodeBytes.Length; i += 2)
        if (unicodeBytes[i] != 0)
            return true;
    return false;
}
public static string SqlEncodingToUtf(this string obj)
{
    return Encoding.UTF8.GetString(Encoding.GetEncoding(1256).GetBytes(obj));
}
public static string ToHex(string str)
{
    var sb = new StringBuilder();
    byte[] bytes = IsUnicode(str) ? Encoding.Unicode.GetBytes(str) : 
                   Encoding.ASCII.GetBytes(str);
    for (int counter = 0; counter < bytes.Length; counter++)
        sb.Append(bytes[counter].ToString("X"));
    return sb.ToString();
}
public static IEnumerable<int> ToInt(IEnumerable<string> array)
{
    return array.Where(str => str.IsNumber()).Select(str => str.ToInt());
}
public static string ToUnicode(this string str)
{
    return Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(str));
}
public static bool EndsWithAny(this string str, IEnumerable<string> values)
{
    return values.Any(str.EndsWith);
}
public static bool StartsWithAny(this string str, IEnumerable<string> values)
{
    return values.Any(str.StartsWith);
}
public static IEnumerable<int> AllIndexesOf(this string str, 
              string value, bool ignoreCase = false)
{
    string buffer = ignoreCase ? str.ToLower() : str;
    string stat = ignoreCase ? value.ToLower() : value;
    int statIndex = 0;
    int currIndex;
    while ((currIndex = buffer.IndexOf(stat)) != -1)
    {
        statIndex += currIndex;
        yield return statIndex;
        statIndex += stat.Length;
        buffer = buffer.Substring(currIndex + stat.Length);
    }
}