LINQ和递归

cll*_*pse 5 c# linq recursion

考虑以下:

public class Box
{
    public BoxSize Size { get; set; }

    public IEnumerable<Box> Contents { get; set; }
}

Box FindBoxBySize(Box box, BoxSize size)
{
    Box _foundBox = null;

    Action<IEnumerable<Box>> _recurse = null;

    _recurse = new Action<IEnumerable<Box>>(boxes =>
    {
        foreach (var _box in boxes)
        {
            if (_box.Size == size)
            {
                _foundBox = _box;

                return;
            }

            if (_box.Contents != null) _recurse(_box.Contents);
        }
    });

    _recurse(box.Contents);

    return _foundBox;
}
Run Code Online (Sandbox Code Playgroud)

有没有什么方法FindBoxBySize()可以使用LINQ压缩?另外:欢迎评论我的代码.我没有做太多的递归,所以我可能在实现中遗漏了一些东西.

Eni*_*ity 5

我也采用扩展方法方法,但使用迭代器方法:

public static class BoxEx
{
    public static IEnumerable<Box> Flatten(this Box box)
    {
        yield return box;
        if (box.Contents != null)
        {
            foreach (var b in box.Contents.SelectMany(b2 => Flatten(b2)))
            {
                yield return b;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你的FindBoxBySize方法现在变成:

Box FindBoxBySize(Box box, BoxSize size)
{
    return (from b in box.Flatten()
            where b.Size == size
            select b).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

您的原始呼叫代码无需修改即可使用

var small = FindBoxBySize(box, BoxSize.Small);
Run Code Online (Sandbox Code Playgroud)