Some C# snippets I Use a Lot

Quick and dirty code with no error checking

Often I want to count occurrences or have a set like function to list unique labels, for this task I use a simple wrapper around the dictionary.

  class Bag<T> : Dictionary<T, int>

  {

    public void Add(T t)

    {

      if (!this.ContainsKey(t))

      {

        this.Add(t, 1);

      }

      this[t]++;

    }

  }

Splitting on whitespaces whilst removing empty fields is another frequent task,  I include this extension method in my projects.

public static class StringEx

  {

    public static String[] SplitOnWhiteSpace(this String s)

    {

      return s.Split(new String[] { "\t", " " },  StringSplitOptions.RemoveEmptyEntries);

    }

  }

I formatted the code using the CopySourceAsHtml Pluing

This entry was posted by Edobashira. Bookmark the permalink.