The follow code will break the list into sub-lists which begins with "[" and end with "]". How to convert it to use yield return so it can handle very huge stream input lazily? --Or how to implement it in F# with lazily enumerating?-- (never mind, I think f#implementation should be trivial)
var list = new List<string> { "[", "1", "2", "3", "]", "[", "2", "2", "]", "[", "3", "]" };
IEnumerable<IEnumerable<string>> result = Split(list);
static IEnumerable<IEnumerable<string>> Split(List<string> list)
{
return list.Aggregate(new List<List<string>>(), // yield return?
(sum, current) =>
{
if (current == "[")
sum.Add(new List<string>());
else if (current == "]")
return sum; // Convert to yield return?
else
sum.Last().Add(current);
return sum; // Convert to yield return?
});
}
C# doesn't support anonymous iterator blocks, so you'll simply need to use a named method instead of an anonymous method.
public static IEnumerable<IEnumerable<string>> Split(IEnumerable<string> tokens)
{
using(var iterator = tokens.GetEnumerator())
while(iterator.MoveNext())
if(iterator.Current == "[")
yield return SplitGroup(iterator);
}
public static IEnumerable<string> SplitGroup(
IEnumerator<string> iterator)
{
while(iterator.MoveNext() && iterator.Current != "]")
yield return iterator.Current;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With