The easiest solution is to use the Split extension method from MoreLINQ :
byte separator=59;
var triplets=largeBytes.Split(separator);
This will return an IEnumerable of IEnumerable<byte>
. You can convert it to an IEnumerable<byte[]>
with ToArray()
:
var triplets=largeBytes.Split(separator).Select(triplet=>triplet.ToArray());
Or you can do roughly what the extension method does - create an iterator that checks each input element until it finds the separator and places each character in an array:
public static IEnumerable<List<T>> Split<T>(this IEnumerable<T> source, T separator)
{
List<T> result=new List<T>(3);
foreach(T item in source)
{
if (item == separator)
{
yield return result;
result=new List<T>(3);
}
else
{
result.Add(item);
}
}
yield return result;
}
You can use this extension method in the same way:
byte separator=59;
var triplets=largeBytes.Split(separator);
or
var triplets=MyExtensionsClass.Split(largeBytes,separator);
MoreLINQ's version is a lot more versatile, as it allows you to specify a maximum number of splits, or transform the input into another form
If you want to include the separator, you put result.Add
before the first if
. A better option would be to add an include
parameter:
public static IEnumerable<List<T>> Split<T>(this IEnumerable<T> source, T separator,bool include=false)
{
List<T> result=new List<T>(3);
foreach(T item in source)
{
if (item == separator)
{
if (include) result.Add(item);
yield return result;
result=new List<T>(3);
}
else
{
result.Add(item);
}
}
yield return result;
}