lambda表达式中的yield return?

时间:2016-02-18 05:21:44

标签: c# linq

以下代码会将列表分成以" ["并以"]"结束。如何将其转换为使用yield return,以便它可以懒惰地处理非常大的流输入? - 或者如何在F#中使用lazily枚举来实现它? - (没关系,我认为f#实现应该是微不足道的)

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?
    });
}

4 个答案:

答案 0 :(得分:5)

C#不支持匿名迭代器块,因此您只需要使用命名方法而不是匿名方法。

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;
}

答案 1 :(得分:0)

虽然在lambda中C#不允许yield,但我认为我们可以解决这个问题

static IEnumerable<IEnumerable<string>> Split(List<string> list)
{
    var tmp = list as IEnumerable<string>;
    while(tmp.FirstOrDefault() == "[")
    {
        yield return tmp.TakeWhile((current) => current != "]");
        tmp = tmp.SkipWhile((current) => current != "]");
    }
}

答案 2 :(得分:-1)

我使用Linq找到了另一种方法。不确定效率,但它确实有效。

int index=0;
list.Select(item=> new { item=item, index= item=="]"? ++index : index })
                  .Where(c => !(c.item == "[" || c.item =="]"))
                  .GroupBy(g=>g.index)
                  .Select(e=> e.Select(c=>c.item));

工作Demo

答案 3 :(得分:-1)

您的任务最简单的解决方案是这种方法:

IEnumerable<IEnumerable<string>> SplitList(IEnumerable<string> list, string open = @"[", string close = @"]") {
    Dictionary<int, List<string>> splitedList = new Dictionary<int, List<string>>();
    int i = 0;            
    foreach (var s in list) {
        if (open.Equals(s))
            splitedList.Add(i, new List<string>());
        else if (close.Equals(s))
            i++;
        else
            splitedList[i].Add(s);
    }
    return splitedList.Values;
}