c# - How To Split a Generic Array -


i want mimic string.split functionality generic arrays.

i have come method seems work doubles.

public static double[][] split(this double[] vals, double t) {     list<double[]> ret = new list<double[]>();      int last = -1;     (int = 0; <= vals.length; i++)     {         if (i != vals.length && vals[i] != t)             continue;          int len = - last - 1;         if (len <= 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(); } 

and 1 generics...

public static t[][] split<t>(this t[] vals, t t) t : equalitycomparer<t> {     list<t[]> ret = new list<t[]>();      int last = -1;     (int = 0; <= vals.length; i++)     {         if (i != vals.length && vals[i] != t)             continue;          int len = - last - 1;         if (len <= 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(); } 

so, have 3 questions:

  1. is there better/generic-c# way of doing this?
  2. how can template method working? (i error on vals[i] != t) - fixed now
  3. how can make better (it kind of ugly right now, imo)

example usage:

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] 

you can use following generic extension method split sequences separator. uses default comparer compare each item separator.

public static ienumerable<t[]> split<t>(this ienumerable<t> source, t separator) {     list<t> bucket = new list<t>();     var comparer = comparer<t>.default;      foreach (var item in source)     {         if (comparer.compare(item, separator) != 0)         {             bucket.add(item);             continue;         }          if (bucket.any())         {             yield return bucket.toarray();             bucket = new list<t>();         }     }      if (bucket.any())                 yield return bucket.toarray();         } 

usage:

double[] vals = new double[] { 0, 1, 2, 0, 0, 2, 3, 0, 4, 5, 6 }; double[][] res = vals.split(0).toarray(); 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -