Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yield return in the lambda expression?

Tags:

c#

linq

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?
    });
}
like image 921
ca9163d9 Avatar asked Jun 21 '26 09:06

ca9163d9


1 Answers

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;
}
like image 177
Servy Avatar answered Jun 23 '26 21:06

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!