title: How To Split a Generic Array
body: <p>I want to mimic the <a href="http://msdn.microsoft.com/en-us/library/system.string.split.aspx" rel="nofollow">String.Split</a> functionality for generic arrays.</p>
  
  <p>I have come up with this method which seems to work for doubles.</p>
  
  <pre><code>public static double[][] Split(this double[] vals, double t)
  {
      List&lt;double[]&gt; ret = new List&lt;double[]&gt;();
  
      int last = -1;
      for (int i = 0; i &lt;= vals.Length; i++)
      {
          if (i != vals.Length &amp;&amp; vals[i] != t)
              continue;
  
          int len = i - last - 1;
          if (len &lt;= 0)
          {
              last = i;
              continue;
          }
  
          double[] arr = new double[len];
          Array.Copy(vals, last + 1, arr, 0, len);
          last = i;
  
          ret.Add(arr);
      }
  
      return ret.ToArray();
  }
  </code></pre>
  
  <p>And this one for generics...</p>
  
  <pre><code>public static T[][] Split&lt;T&gt;(this T[] vals, T t) where T : EqualityComparer&lt;T&gt;
  {
      List&lt;T[]&gt; ret = new List&lt;T[]&gt;();
  
      int last = -1;
      for (int i = 0; i &lt;= vals.Length; i++)
      {
          if (i != vals.Length &amp;&amp; vals[i] != t)
              continue;
  
          int len = i - last - 1;
          if (len &lt;= 0)
          {
              last = i;
              continue;
          }
  
          T[] arr = new T[len];
          Array.Copy(vals, last + 1, arr, 0, len);
          last = i;
  
          ret.Add(arr);
      }
  
      return ret.ToArray();
  }
  </code></pre>
  
  <p>So, I have three questions:</p>
  
  <ol>
  <li>Is there a better/generic-C# way of doing this?</li>
  <li>How can I get the template method working? (I get an error on <code>vals[i] != t</code>) - Fixed now</li>
  <li>How can I make this better (It is kind of ugly right now, IMO)</li>
  </ol>
  
  <p>Example Usage:</p>
  
  <pre><code>double[] vals = new double[] { 0, 1, 2, 0, 0, 2, 3, 0, 4, 5, 6 };
  double[][] res = vals.Split(0);
  
  // res[0] = [1, 2]
  // res[1] = [2, 3]
  // res[2] = [4, 5, 6]
  </code></pre>